<?php
class adminMod extends commonMod {
    public function index()
    {
        $this->display("admin/loginnew");//输出模板
    }

    public function register(){
        $type=$_POST['type'];
        $username = $_POST['USERNAME'];
        $password = md5($_POST['PASSWORD']);
        $NAME = $_POST['NAME'];
        $EMAIL = $_POST['EMAIL'];
        $sql="SELECT * FROM `h_admin` WHERE `username`='{$username}' and `other`='{$type}'";
        $list  =   $this->model->query($sql);
        if($list){
            $json= '{"msg":"1"}';
//            $this->error('此用户名已注册，请更换用户名');
        }else{
            if($type=='office'){
                $level=0;
            }else{
                $level=8;
            }
            $sql="INSERT INTO `h_admin`( `username`, `password`, `uname`, `email`, `other`,level) VALUES('{$username}','{$password}','{$NAME}','{$EMAIL}','{$type}','{$level}')";
            $list  =   $this->model->query($sql);
//            $this->error('注册成功');
            $json= '{"msg":"2"}';
        }
        echo $json;
    }
    public function checkuser()	{
        $username = $_POST['username'];
        $password = $_POST['password'];
        $verify = $_POST['verify'];
        if($verify!=$_SESSION['authnum_session']){
            $this->error('验证码错误');
        }
        if(empty($username)){
            $this->error('请输入用户名');
        }
        $condition = " username='".$username."' ";
        $info = $this->model->table('h_admin')->where($condition)->find();
        if($info['id']){
            $condition .= " and password='".md5($password)."' ";
            $info = $this->model->table('h_admin')->where($condition)->find();
            if($info['id']){
                $type=$info['other'];
                if($type=='office'){
                    $company= $this->model->query("SELECT * FROM `h_company` WHERE `addadminId`=".$info['id']);
                    if(!$company){
                        $this->redirect(__APP__."/index/AuthenticationOffice");
                    }
                }
                $this->_login($username,$info['id'],$info['level'],$info['uname']);

                $_SESSION['manage_department']=$info['department'];
                $_SESSION['manage_post']=$info['post'];
                $_SESSION['manage_phone']=$info['phone'];
                $_SESSION['manage_landline']=$info['landline'];
                $_SESSION['manage_email']=$info['email'];
                $_SESSION['manage_other']=$info['other'];

                $permission=$_SESSION['manage_permission'];
                $perArry=explode(',',$permission);

                $menuIdFirest= $perArry[0];
                $menuInfo = $this->model->table('h_navigation_menu')->where("`id` = '{$menuIdFirest}'")->find();
                if($menuInfo){
                    $menuStr= '/'.$menuInfo['functionMod'].'/'.$menuInfo['menuLabel'];
                }else{
                    $menuStr = "/admin" ;
                }
                $this->redirect(__APP__.$menuStr);
//                if(strstr($p,"manage_hinfo,")){
//                    $this->redirect(__APP__."/admin/hinfo");
//                }else{
//                    $perArry=explode(',',$p);
//                    $prfFirst=explode('_',$perArry[0]);
//                    $leftFirdt=$prfFirst[1];
//                    $this->redirect(__APP__."/admin/".$leftFirdt);
//                }
//				$this->redirect(__APP__."/admin/admin_index");
            }else{
                $this->error('密码错误，请重新输入');
            }
        }else{
            $this->error('用户名不存在，请重新输入');
        }
        $this->display("index/login");//输出模板
    }

    //用户登录
    private function _login($username,$userid,$groupid,$uname)
    {
        $condition["id"] = $userid;
        //更新帐号信息
        $data=array();
        $data['login_time']=time();
        $data['login_ip']=get_client_ip();
        $this->model->table('h_admin')->data($data)->where($condition)->update();
        $sql = " select * from h_permission where id=".$groupid;
        $list  =   $this->model->query($sql);

        if($list){
            $permission= substr($list[0]['permission'],0,-1);
        }
        unset($list);

        $navigationMenuArry=array();
        $MenuConfigArry=array();

        $sql= "SELECT mf.`menuName` as pmenuName,mf.`menuLabel` as pmenuLabel,mc.* FROM `h_navigation_menu` mf left join `h_navigation_menu` mc on mf.id=mc.pid WHERE mf.pid=0 and mc.state=1 and mf.state=1 and mc.id in (".$permission.") order by mf.morder,mc.morder";

        $navigationMenu= $this->model->query($sql);

        foreach($navigationMenu as $v){
            $pmenuName = $v['pmenuName'];
            $pmenuLabel = $v['pmenuLabel'];
            $menuName=$v['menuName'];
            $navigationMenuArry[$pmenuLabel]['pmenuName']=$pmenuName;
            $navigationMenuArry[$pmenuLabel]['pmenuLabel']=$pmenuLabel;
            if($menuName){
                $child=array(
                    'menuName'=>$v['menuName'],
                    'menuLabel'=>$v['menuLabel'],
                    'functionMod'=>$v['functionMod'],
                    'icon'=>$v['icon'],
                );
                $navigationMenuArry[$pmenuLabel]['child'][]=$child;

                $childMenu=array(
                    'menuName'=>$v['menuName'],
                    'menuLabel'=>$v['menuLabel'],
                    'functionMod'=>$v['functionMod'],
                    'pmenuName'=>$pmenuName
                );
                $MenuConfigArry[$v['menuLabel']]=$childMenu;
            }
        }
        $_SESSION['manage_MenuConfigArry']=$MenuConfigArry;
        $_SESSION['manage_navigationMenuArry']=$navigationMenuArry;

        //设置登录信息
        $_SESSION['manage_uid']=$userid;
        $_SESSION['manage_groupid']=$groupid;
        $_SESSION['manage_permission']=$permission;
        $_SESSION['manage_username']=$username;
        $_SESSION['manage_uname']=$uname;
        $_SESSION['__ROOT__']=__ROOT__;
        return true;
    }
//用户退出
    public function logout()
    {
        $nowuid = $_SESSION['manage_uid'];
        $sql = "update h_admin set last_login_time = login_time where id = ".$nowuid;
        $this->model->query($sql);
        unset($_SESSION['manage_uid']);
        unset($_SESSION['manage_username']);
        unset($_SESSION['manage_permission']);
        unset($_SESSION['manage_groupid']);
        unset($_SESSION['manage_uname']);
        unset($_SESSION['manage_MenuConfigArry']);
        unset($_SESSION['manage_navigationMenuArry']);
        unset($_SESSION['__ROOT__']);
        $this->success('您已成功退出系统',__APP__."/admin");
    }

    //上传图片资源
    public function uploadPic(){
        if($_FILES){
            require(CP_PATH.'ext/UploadFile.class.php');//加载上传修改类
            $filestr = '';
            $arr= $this->_upload($filestr);
            $addr="images/".str_replace(' ', '', $arr[0][savename]);
            echo '{"addr":"'.$addr.'"}';
        }
    }

    //企业信息管理
    public function companyInfo(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=10;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);
        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }
        $adminId = $_SESSION['manage_uid'];
        $sql = "select * from h_company where addadminId='{$adminId}' order by id ".$limitStr ;

        $list  =   $this->model->query($sql);
        $count=count($list);
        $this->assign('count',$count);
        if($listRows>=$count){
            $this->assign('page','');
        }else{
            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
        }
        if(count($list)){
            $this->assign("Arr",$list);
        }

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['companyInfo']);
        $this->display("admin/companyInfo");
    }


    //添加、修改企业信息
    public function editCompany(){
        $chargerName = $_POST['chargerName'];
        $companyName = $_POST['companyName'];
        $industry = $_POST['industry'];
        $tel = $_POST['tel'];
        $email = $_POST['email'];
        $address = $_POST['address'];
        $orgCode =  $_POST['orgCode'];
        $demand=  $_POST['demand'];
        $id =  $_POST['id'];

        $con='';
        if($demand){
            $con=",demand='{$demand}'";
        }

        if(empty($companyName)){
            $this->error('公司名称不能为空！');
        }
        if(empty($chargerName)){
            $this->error('负责人名不能为空！');
        }
        if(empty($tel)){
            $this->error('联系电话不能为空！');
        }

        $adminId = $_SESSION['manage_uid'];
        $row = $this->model->query("select * from h_company where id ='".$id."'");
        if($row){
            $sql="UPDATE `h_company` SET `chargerName`='{$chargerName}',`companyName`='{$companyName}',`industry`='{$industry}',`orgCode`='{$orgCode}',`email`='{$email}',`tel`='{$tel}',`address`='{$address}'".$con." WHERE id='{$id}'";
            $row = $this->model->query($sql);
            if($row){
                $this->error('修改成功！');
            }
        }else {
            if(empty($demand)){
                $this->error('营业执照不能为空！');
            }
            $addtime = date('Y-m-d H:i:s',time());
            $sql="INSERT INTO `h_company`(`chargerName`, `companyName`, `industry`, `orgCode`, `addtime`, `addadminId`, `demand`, `email`, `tel`,  `address`)VALUES
('{$chargerName}','{$companyName}','{$industry}','{$orgCode}','{$addtime}','{$adminId}','{$demand}','{$email}','{$tel}','{$address}')";
            $row = $this->model->query($sql);
            if($row){
                $json= '{"msg":"1"}';
                echo $json;
            }
        }


    }

    //企业信息管理
    public function postInfo(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=10;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);
        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }
        $adminId = $_SESSION['manage_uid'];
        $sql = "select * from h_postinfo where addadminId='{$adminId}' order by id ".$limitStr ;

        $list  =   $this->model->query($sql);
        $count=count($list);
        $this->assign('count',$count);
        if($listRows>=$count){
            $this->assign('page','');
        }else{
            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
        }
        if(count($list)){
            $this->assign("Arr",$list);
        }

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['postInfo']);
        $this->display("admin/postInfo");
    }


    //添加、性格岗位信息
    public function editPost(){
        $postName = $_POST['postName'];
        $postCode = $_POST['postCode'];
        $characterName = $_POST['characterName'];
        $number = $_POST['number'];
        $characterNo = $_POST['characterNo'];
        $score = $_POST['score'];

        $id =  $_POST['id'];

        if(empty($postName)){
            $this->error('岗位名称不能为空！');
        }
        if(empty($postCode)){
            $this->error('岗位编号不能为空！');
        }
        if(empty($number)){
            $this->error('需求人数不能为空！');
        }
        $adminId = $_SESSION['manage_uid'];
        $row = $this->model->query("select * from h_postinfo where id ='".$id."'");
        if($row){
            $sql="UPDATE `h_postinfo` SET `postName`='{$postName}',`number`='{$number}',`postCode`='{$postCode}',`characterNo`='{$characterNo}',`characterName`='{$characterName}',`score`='{$score}' WHERE id='{$id}'";
            $row = $this->model->query($sql);
            if($row){
                $this->error('修改成功！');
            }
        }else {
            $addtime = date('Y-m-d H:i:s',time());
            $sql="INSERT INTO `h_postinfo`( `postName`, `number`, `postCode`, `addtime`, `addadminId`, `characterNo`, `characterName`, `score`) VALUES 
('{$postName}','{$number}','{$postCode}','{$addtime}','{$adminId}','{$characterNo}','{$characterName}','{$score}')";
            $row = $this->model->query($sql);
            if($row){
                $this->error('添加成功！');
            }
        }
    }

    //岗位删除
    public function delallPost(){
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        foreach ($strArr as $val){
            $sql = "delete from h_postinfo where id=".$val ;
            $row = $this->model->query($sql);
        }
        $json ='{"msg":"'.$row.'"}';
        unset($row);
        echo $json;
        exit;
    }


    //个人测评
    public function evaluation(){
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['evaluation']);
        $this->display("admin/Evaluation");
    }



    public function admin_index()
    {
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=10;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $con="";
//        $condition=" id > 0 ";
        $mingcheng=$_GET['roomid'];

        if($mingcheng){
            $con =$con." and f.roomNo like '%".$mingcheng."%' ";
        }

        $ehouse=$_GET['hotelname'];
        if($ehouse){
            $con = $con."  and h.hotel ='".$ehouse."' " ;
        }

        $filmname=$_GET['filmname'];
        if($filmname){
            $con =$con. "  and f.filename like '%".$filmname."%' " ;
        }

//        $count = $this->model->table('h_filmorder')->where($condition)->count();
        $sql = "select count(*) as zs from h_filmorder f left join h_hotels h on h.hotelName=f.hotelName where f.id > 0 ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }

        $sql="select f.*,h.hotel from h_filmorder f left join h_hotels h on h.hotelName=f.hotelName where f.id > 0 ".$con." order by f.id desc ".$limitStr;

        $list  =   $this->model->query($sql);
        $this->assign('count',$count);
        if($listRows>=$count){
            $this->assign('page','');
        }else{
            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
        }
        if(count($list)){
            $this->assign("krhjArr",$list);
        }
        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['admin_index']);
        $this->display("admin/admin_index");
    }

    //酒店状态
    public function hinfo(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $rname = $_GET['rname'];
        $con=" where h.id>0 ";
        if($rname){
            $con =$con."  and  h.hotel like '%".$rname."%' ";
        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=25;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $cong='';
        }

        $sql = "select count(h.id) as zs from h_hotels h ".$consql_g.$con.$cong;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select h.* from h_hotels h  ".$consql_g.$con.$cong."  order by h.id  ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("roomArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }
        unset($row);
        unset($list);

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['hinfo']);
        $this->display("admin/hinfo");

    }
    //数据统计
    public function sjtj(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $hotelname = $_GET['hotelname'];
        $stime = $_GET['stime'];
        $etime = $_GET['etime'];

        $con='';
        $con_view='';
        if($hotelname){
            $con =$con." and  hotelid =".$hotelname;
            $con_view =$con_view." and  h.hotel like '%".$hotelname."%' ";
        }
        if($stime){
            $con =$con." and  stime >= '".$stime."' ";
            $con_view =$con_view." and  r.uploaddate >= '".$stime."' ";
        }
        if($etime){
            $con =$con." and  stime <= '".$etime."' ";
            $con_view =$con_view." and  r.uploaddate <= '".$etime."' ";
        }

//        $starttime=date("Y-m-d",strtotime("last month"));//初始化时间
//        $endtime=date('Y-m-d',time());
//
//        $this->assign("starttime",$starttime);
//        $this->assign("endtime",$endtime);

        //  $time=date('Y-m-d',time());
//
        $sqlc="SELECT count(*) as c,hotel FROM `h_hotels_data` WHERE id>0 ".$con;
        $row= $this->model->query($sqlc);
        $count=$row[0]['c'];
        if($listRows>=$count){
            $this->assign('page','');
        }else{
            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
        }
        if($hotelname){
            $hotel_name=$row[0]['hotel'];
            $this->assign("hotel_name",$hotel_name);
        }


        $sql="SELECT * FROM `h_hotels_data` group by hotel";
        $list  =   $this->model->query($sql);
        if($list){
            $this->assign("hotelArr",$list);
        }



//        $sql="SELECT sum(clientNo) as clientNo ,sum(movielength) as totalMovielth, sum(tvlength) as totalTvlth ,sum(tourlength) as totalTourlth ,sum(totallength) as totalLth ,sum(tourRooms) as totalTourRooms FROM `h_hotels_data` WHERE id>0 ".$con;
//        $list  =   $this->model->query($sql);
//        if($list){
//            $this->assign("listArr",$list);
//            $Movielth=round($list[0]['totalMovielth'],3);
//            $Tvlth=round($list[0]['totalTvlth'],3);
//            $totalLth=round($list[0]['totalLth'],3);
//            $totalTourlth=round($list[0]['totalTourlth'],3);
//            $otherlth=$totalLth-$Movielth-$Tvlth-$totalTourlth;

//            $Movielthper=100*$list[0]['totalMovielth']/$totalLth;
//            $Tvlthper=100*$list[0]['totalTvlth']/$totalLth;
//            $totalTourlthper=100*$list[0]['totalTourlth']/$totalLth;
//
//            $otherlthper=100-$Movielthper-$Tvlthper-$totalTourlthper;
//
//            $piedata="[['电影总时长',$Movielthper], ['旅游视频',$totalTourlthper],{
//                            name: '电视总时长',
//                            y: $Tvlthper,
//                            sliced: true,
//                            selected: true
//                        },['其他时长',$otherlthper]]";
//            $this->assign("piedata",$piedata);
//        }


        $sql="SELECT sum(clientNo) as clientNo  ,sum(tourRooms) as totalTourRooms FROM `h_hotels_data` WHERE id>0 ".$con;
        $list  =   $this->model->query($sql);
        if($list){
            $this->assign("listArr",$list);
        }
        $sql="SELECT sum(duration) as length,apkName,package FROM `h_hotels_data_apk` WHERE id>0 ".$con." group by package order by length desc";
        $list  =   $this->model->query($sql);
        if($list){
            $totalLth=$list[0]['length'];
            $this->assign("apklistArr",$list);

            $apk_name1=$list[1]['apkName'];
            $apk_length1=$list[1]['length'];
            $apk_length1_per=100*$apk_length1/$totalLth;
            $strPie="{name:'".$apk_name1."',
                   y:$apk_length1_per,
                   sliced: true,
                   selected: true},";

            $apkArray=array_slice($list,2) ;
            $other=$totalLth-$apk_length1;
            foreach($apkArray as $var){
                $apk_name=$var['apkName'];
                $apk_length=$var['length'];
                $other=$other-$apk_length;
                $apk_length_per=100*$apk_length/$totalLth;
                $strPie=$strPie."['".$apk_name."',$apk_length_per],";
            }
            $other_length_per=100*$other/$totalLth;
            $strPie=$strPie."['其他',$other_length_per]";
            $piedata="[$strPie]";

            $this->assign("piedata",$piedata);
        }

        $sqlMmax="SELECT SUM( r.data_num ) AS c, r.data_name FROM  `h_ranking` r LEFT JOIN h_hotels h ON r.hotelid = h.id WHERE  r.flag =  'Mmax' ".$con_view." GROUP BY r.data_name ORDER BY c DESC LIMIT 0 , 10";
        $rowMmax =   $this->model->query($sqlMmax);
        if($rowMmax){
            $categoriesMmax="[";
            $dataMmax="[";
            foreach($rowMmax as $var){
                $categoriesMmax=$categoriesMmax."'".$var['data_name']."',";
                $dataMmax=$dataMmax.$var['c'].",";
            }
            $categoriesMmax=substr($categoriesMmax,0,-1);
            $categoriesMmax=$categoriesMmax."]";
            $dataMmax=substr($dataMmax,0,-1);
            $dataMmax=$dataMmax."]";
        }
        if(!$categoriesMmax){
            $categoriesMmax=0;
        }
        if(!$dataMmax){
            $dataMmax=0;
        }
        $this->assign("categoriesMmax",$categoriesMmax);
        $this->assign("dataMmax",$dataMmax);

        $sqlTmax="SELECT SUM( r.data_num ) AS c, r.data_name FROM  `h_ranking` r LEFT JOIN h_hotels h ON r.hotelid = h.id WHERE  r.flag =  'Tmax' ".$con_view." GROUP BY r.data_name ORDER BY c DESC LIMIT 0 , 10";
        $rowTmax =   $this->model->query($sqlTmax);
        if($rowTmax){
            $categoriesTmax="[";
            $dataTmax="[";
            foreach($rowTmax as $var){
                $categoriesTmax=$categoriesTmax."'".$var['data_name']."',";
                $dataTmax=$dataTmax.$var['c'].",";
            }
            $categoriesTmax=substr($categoriesTmax,0,-1);
            $categoriesTmax=$categoriesTmax."]";
            $dataTmax=substr($dataTmax,0,-1);
            $dataTmax=$dataTmax."]";
        }
        if(!$categoriesTmax){
            $categoriesTmax=0;
        }
        if(!$dataTmax){
            $dataTmax=0;
        }
        $this->assign("categoriesTmax",$categoriesTmax);
        $this->assign("dataTmax",$dataTmax);

        $sqlMmin="SELECT SUM( r.data_num ) AS c, r.data_name FROM  `h_ranking` r LEFT JOIN h_hotels h ON r.hotelid = h.id WHERE  r.flag =  'Mmin' ".$con_view." GROUP BY r.data_name ORDER BY c DESC LIMIT 0 , 10";
        $rowMmin =   $this->model->query($sqlMmin);
        if($rowMmin){
            $categoriesMmin="[";
            $dataMmin="[";
            foreach($rowMmin as $var){
                $categoriesMmin=$categoriesMmin."'".$var['data_name']."',";
                $dataMmin=$dataMmin.$var['c'].",";
            }
            $categoriesMmin=substr($categoriesMmin,0,-1);
            $categoriesMmin=$categoriesMmin."]";
            $dataMmin=substr($dataMmin,0,-1);
            $dataMmin=$dataMmin."]";

        }
        if(!$categoriesMmin){
            $categoriesMmin=0;
        }
        if(!$dataMmin){
            $dataMmin=0;
        }
        $this->assign("categoriesMmin",$categoriesMmin);
        $this->assign("dataMmin",$dataMmin);

        $sqlTmin="SELECT SUM( r.data_num ) AS c, r.data_name FROM  `h_ranking` r LEFT JOIN h_hotels h ON r.hotelid = h.id WHERE  r.flag =  'Tmin' ".$con_view." GROUP BY r.data_name ORDER BY c DESC LIMIT 0 , 10";
        $rowTmin =   $this->model->query($sqlTmin);
        if($rowTmin){
            $categoriesTmin="[";
            $dataTmin="[";
            foreach($rowTmin as $var){
                $categoriesTmin=$categoriesTmin."'".$var['data_name']."',";
                $dataTmin=$dataTmin.$var['c'].",";
            }
            $categoriesTmin=substr($categoriesTmin,0,-1);
            $categoriesTmin=$categoriesTmin."]";
            $dataTmin=substr($dataTmin,0,-1);
            $dataTmin=$dataTmin."]";
        }
        if(!$categoriesTmin){
            $categoriesTmin=0;
        }
        if(!$dataTmin){
            $dataTmin=0;
        }
        unset($rowTmax);
        unset($rowMmax);
        unset($rowTmin);
        unset($rowMmin);
        unset($row);
        unset($list);
        $this->assign("categoriesTmin",$categoriesTmin);
        $this->assign("dataTmin",$dataTmin);


        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['sjtj']);
        $this->display("admin/sjtj");

    }


    //管理电影
    public function dygl(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $con="where id>0 ";
        $filmname= $_GET['filmname'];
        if($filmname){
            $con =$con."  and movie_name like '%".$filmname."%' ";
        }
        $filmnemu= $_GET['filmnemu'];
        if($filmnemu){
            $con =$con." and  movie_content like '%".$filmnemu."%' ";
        }
        $mprice= $_GET['mprice'];
        if($mprice){
            $con =$con." and  substring_index(substring_index(movie_content,'#',2),'#',-1) =".$mprice;
        }

        $stime= $_GET['stime'];
        if($stime){
            $con =$con." and  movie_stime >= '".strtotime($stime)."' ";
        }
        $etime= $_GET['etime'];
        if($etime){
            $con =$con." and  movie_stime <='".strtotime($etime)."' ";
        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $sql = "select count(*) as zs from h_movies ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select * from h_movies   ".$con."  order by movie_stime,morder desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("movieArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }
        $this->hotelSelect();
        $this->movieSelect();

        $sql="SELECT * FROM `h_moviemenu` WHERE 1 order by morder";
        $row = $this->model->query($sql);
        if($row){
            $this->assign("menuArr",$row);
        }
        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
        $this->display("admin/dygl");

    }

//电影文件上传
    public function moiveEdit()
    {
        $time=time();
        $id=$_POST['id'];
        $Issuer = $_POST['Issuer'];
        $movie_name = $_POST['movie_name'];
        if(!$movie_name){
            $this->error('电影名字不能为空');
        }
        $movie_addr=$_POST['movie_addr'];
        if(!$movie_addr){
            $this->error('电影路径不能为空');
        }
        $movie_pic=$_POST['movie_pic'];
        $movie_post=$_POST['movie_post'];
        $movie_trailer=$_POST['movie_trailer'];//片花路径

        $details =  $_POST['details'];//详情
        $director =  $_POST['director'];
        $actor =  $_POST['actor'];
        $movie_price=$_POST['movie_price'];

        $hot =  $_POST['hot'];
        $movie_length =  $_POST['movie_length'];
        $movie_area =  $_POST['movie_area'];
        $showtime=$_POST['showtime'];
        $label=$_POST['label'];
        $score =  $_POST['score'];
        $playtimes =  $_POST['playtimes'];
        $resolution=  $_POST['resolution'];//分辨率
        $movie_menu=$_POST['movie_menu'];
        $language=$_POST['language'];
        $movie_ss=$_POST['movie_ss'];
        $morder=$_POST['morder']?$_POST['morder']:0;
        if(!$movie_menu){
            $this->error('电影分类不能为空');
        }

        //简介@导演@主演@热度@时长@地区@上映时间@标签类型@评分@播放次数@分辨率@排序
        $movie_content=$movie_menu.'#'.$movie_price.'#'.$details.'@'.$director.'@'.$actor.'@'.$hot.'@'.$movie_length.'@'.$movie_area.'@'.$showtime.'@'.$label.'@'.$score.'@'.$playtimes.'@'.$resolution.'@'.$morder.'#'.$language.'#'.$movie_ss;
        if ($id){
            $sql="UPDATE `h_movies` SET `movie_name`='".$movie_name."',`movie_addr`='".$movie_addr."',`movie_trailer`='".$movie_trailer."',`movie_pic`='".$movie_pic."',`movie_post`='".$movie_post."',`movie_content`='".$movie_content."',Issuer='".$Issuer."' WHERE id=".$id;
            $this->addStaffLog('修改电影','修改电影：'.$movie_name,'movie');
            //  $this->model->query($sql);
        }else {
            $sql="INSERT INTO `h_movies`( `movie_name`, `movie_addr`,`movie_trailer`, `movie_pic`, `movie_post`, `movie_content`,  `movie_stime`,Issuer) VALUES ('{$movie_name}','{$movie_addr}','{$movie_trailer}','{$movie_pic}','{$movie_post}','{$movie_content}','{$time}','{$Issuer}')";
            $this->addStaffLog('添加电影','添加电影：'.$movie_name,'movie');
        }

        $this->model->query($sql);
        $this->redirect(__APP__."/admin/dygl");
    }

    //电影删除
    public function delallmovie(){

        $hotelname = $_POST['hotelname'];
        if(!$hotelname){
            $this->error("酒店不能为空，请选择");
        }
        $moviename=$_POST['moviename'];
        if(!$moviename){
            $this->error("电影不能为空，请选择");
        }

        $hotelid =  substr($hotelname, 0, -1);
        $hotelidArr=explode(',',$hotelid);
        $movieid=  substr($moviename, 0, -1);
        $movieidArr=explode(',',$movieid);
        foreach($movieidArr as $midval){
            $marr=explode('/',$midval);
            $mid=$marr[0];
            $movie=$marr[1];
            $sql = "UPDATE `h_movies` SET`movie_state`=2 WHERE  id=".$mid;
            $row = $this->model->query($sql);

            $sql_dis="INSERT INTO `h_distribute`(`hotelid`, `hotelname`, `movieid`, `moviename`, `state`) VALUES ";
            $sql_str='';
            foreach($hotelidArr as $hidval){
                $harr=explode('/',$hidval);
                $hid=$harr[0];
                $hotel=$harr[1];
                $sql_str=$sql_str."('{$hid}','{$hotel}','{$mid}','{$movie}',11),";
            }
            $sql_str=substr($sql_str,0,-1);
            $sql_c=$sql_dis.$sql_str;
            $this->model->query($sql_c);
        }

        unset($row_hotel);
        unset($row);
        $this->addStaffLog('下架电影','下架电影：'.$movie,'movie');
        $this->redirect(__APP__."/admin/dygl");
    }

    //分发管理
    public function ffgl(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $mname = $_GET['mname'];
        $hname = $_GET['hname'];
        $state = $_GET['state'];
        $con=" where d.state !=9 ";
        if($hname){
            $con =$con." and  d.hotelname like '%".$hname."%' ";
        }
        if($mname){
            $con =$con." and  d.moviename like '%".$mname."%' ";
        }
        if($state){
            $con =$con." and  d.state =".$state;
        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on d.hotelid=a.hotelId ';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $cong='';
        }

        //  $sql="select d.*,m.movie_addr,m.movie_pic,h.ipaddr from h_distribute d left join h_hotels h on d.hotelid=h.id left join h_movies m on d.movieid=m.id ";
        $sql = "select count(d.id) as zs from h_distribute d ".$consql_g.$con.$cong;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select d.* from h_distribute d ".$consql_g.$con.$cong."  order by d.id desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("contentArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }

        $this->hotelSelect();
        $this->movieSelect();

        unset($row_movie_sql);
        unset($row);
        unset($list);

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['ffgl']);
        $this->display("admin/ffgl");

    }
    //搜索包名
    public function sou_payname(){
        $json ='{';
        $movie_sou = $_POST['arr'];

        $con_movie='';
        if($movie_sou){
            $con_movie="where pname	 like '%".$movie_sou."%' ";
        }
        $sql="SELECT * FROM `p_allpayname` ".$con_movie;
        $row = $this->model->query($sql);
        $this->assign("moviesArr",$row);
        $json_row=json_encode($row);
        $json .='"msg":"1","moviesArr":'.$json_row.'}';
        unset($row);
        echo $json;
        exit;
    }
    public function sou_content(){
        $json ='{';
        $movie_sou = $_POST['arr'];

        $con_movie='';
        if($movie_sou){
            $con_movie="where movie_name	 like '%".$movie_sou."%' ";
        }
        $sql="SELECT * FROM `h_movies` ".$con_movie;
        $row = $this->model->query($sql);
        $this->assign("moviesArr",$row);
        $json_row=json_encode($row);
        $json .='"msg":"1","moviesArr":'.$json_row.'}';
        unset($row);
        echo $json;
        exit;
    }
    public function sou_hotel(){
        $json ='{';
        $movie_sou = $_POST['arr'];

        $con_movie=' where h.id>0 ';
        if($movie_sou){
            $con_movie=$con_movie." and h.hotel	like '%".$movie_sou."%' ";
        }

        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $cong='';
        }

        $sql="SELECT h.* FROM `h_hotels` h ".$consql_g.$con_movie.$cong;

        $row = $this->model->query($sql);
        $this->assign("moviesArr",$row);
        $json_row=json_encode($row);
        $json .='"msg":"1","moviesArr":'.$json_row.'}';
        unset($row);
        echo $json;
        exit;
    }
    public function ffglEdit()
    {
        $id=$_POST['id'];
        $endtime = $_POST['endtime'];
        $starttime=$_POST['starttime'];
        $hotelname = $_POST['hotelname'];
        $price=$_POST['movieprice'];
        if(!$hotelname){
            $this->error("酒店不能为空，请选择");
        }
        $moviename=$_POST['moviename'];
        if(!$moviename){
            $this->error("电影不能为空，请选择");
        }
        if($id){
            $sqls="SELECT * FROM `h_distribute` WHERE id=".$id;
            $rows = $this->model->query($sqls);
            if($rows){
                $price_pre=$rows[0]['content'];
            }
            $sql="UPDATE `h_distribute` SET `content`='{$price}',`starttime`='{$starttime}',`endtime`='{$endtime}' WHERE id=".$id;
            $row = $this->model->query($sql);
            if($price_pre!=$price){

                $content='任务id'.$id.'-酒店:'.$hotelname.'-电影:'.$moviename.'-价格 '.$price_pre.'改为 '.$price;
            }else{
                $content='任务id'.$id.'-酒店:'.$hotelname.'-电影:'.$moviename.' 分发时间修改';
            }
            $this->addStaffLog('修改分发任务','修改分发任务：'.$content,'task');
        }else{
            $hotelid =  substr($hotelname, 0, -1);
            $hotelidArr=explode(',',$hotelid);
            $movieid=  substr($moviename, 0, -1);
            $movieidArr=explode(',',$movieid);
            $content='';
            foreach ($hotelidArr as $hidval){
                $harr=explode('/',$hidval);
                $hid=$harr[0];
                $hotel=$harr[1];
                foreach($movieidArr as $midval){
                    $marr=explode('/',$midval);
                    $mid=$marr[0];
                    $movie=$marr[1];
                    $pricepre=$marr[2];
                    if($price){
                        $pricenow=$price;
                    }else{
                        $pricenow=$pricepre;
                    }
                    $sql="INSERT INTO `h_distribute`( `hotelid`, `hotelname`, `movieid`, `moviename`,`content`,`starttime`, `endtime`) VALUES ('{$hid}','{$hotel}','{$mid}','{$movie}','{$pricenow}','{$starttime}','{$endtime}')";
                    $row = $this->model->query($sql);
                    $id=mysql_insert_id();
                    $content=$content.'任务id'.$id.'-酒店:'.$hotel.'-电影:'.$movie.'；';
                }
            }
            $this->addStaffLog('添加分发任务','添加分发任务：'.$content,'task');
        }
        unset($row);
        unset($rows);
        $this->redirect(__APP__."/admin/ffgl");
    }

    public function startTask(){
        $json ='{';
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        foreach ($strArr as $val){

            $row = $this->model->query("SELECT * FROM `h_distribute` WHERE id=".$val);
            if($row){
                $state=$row[0]['state'];
                if($state<10){
                    $flag=1;
                }elseif($state>20){
                    $flag=22;
                }else{
                    $flag=12;
                }
            }
            $sql = "UPDATE `h_distribute` SET `state`=".$flag." WHERE id=".$val;
            $this->model->query($sql);
        }
        $this->addStaffLog('更新任务','开始任务id：'.$ids,'task');
        $json .='"msg":"1"}';
        unset($row);
        echo $json;
        exit;
    }
    //分发任务删除
    public function delallffgl(){
        $json ='{';
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $content='';
        foreach ($strArr as $val){
            $sqls="SELECT * FROM `h_distribute` WHERE id=".$val;
            $rows = $this->model->query($sqls);
            $hotel=$rows[0]['hotelname'];
            $movie=$rows[0]['moviename'];
            $content=$content.'任务id'.$val.'-酒店:'.$hotel.'-电影:'.$movie.'；';
            //  $sql = "delete from h_distribute where id=".$val;
            //删除任务需要下发，隐藏
            $sql = "UPDATE `h_distribute` SET `state`=9 WHERE id=".$val;
            $row = $this->model->query($sql);
        }
        $this->addStaffLog('删除分发任务','删除分发任务：'.$content,'task');
        $json .='"msg":"1"}';
        unset($row);
        unset($rows);
        echo $json;
        exit;
    }
    //管理电影分类
    public function dyfl(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $mname = $_GET['mname'];
        if($mname){

            $con ="  where  menu_name like '%".$mname."%' ";
        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $sql = "select count(*) as zs from h_moviemenu ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }

        $sql = "select * from h_moviemenu  ".$con."  order by morder  ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $moviesArr=array();
            foreach($list as $var){
                $menu_name=$var['menu_name'];
                $id=$var['id'];
                $morder=$var['morder'];
                $sqln="select count(*) as num from  h_movies where movie_state<2 and movie_content like '%".$menu_name."%'";
                $listn  =   $this->model->query($sqln);
                $num=$listn[0]['num'];
                $listmenu = array(
                    'id' => $id,
                    'menu_name' => $menu_name,
                    'morder' =>  $morder,
                    'num' =>  $num
                );
                array_push($moviesArr,$listmenu);
            }
            $this->assign('count',$count);
            $this->assign("moviesArr",$moviesArr);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }
        unset($row);
        unset($list);

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dyfl']);
        $this->display("admin/dyfl");

    }

//修改电影分类
    public function moivemenuEdit()
    {
        $id=$_POST['id'];

        $menu_name = $_POST['menu_name'];
        $morder=$_POST['morder'];
        $menu_nameEdit = $_POST['menu_nameEdit'];

        if ($id){
            $row_menu=$this->model->query("SELECT morder FROM `h_moviemenu` WHERE id=".$id);
            $morderPer=$row_menu[0]['morder'];
            if($menu_nameEdit){
                $sql_movie="SELECT id,movie_content FROM `h_movies` WHERE movie_content like '%".$menu_name."%' ";
                $row_movie=$this->model->query($sql_movie);
                if($row_movie){
                    foreach($row_movie as $var){
                        $menu_name=$menu_name.'/'.$morderPer;
                        $menu_nameEdit=$menu_nameEdit.'/'.$morder;
                        $new_count=str_replace($menu_name,$menu_nameEdit,$var['movie_content']);
                        $sql_update="UPDATE `h_movies` SET `movie_content`='".$new_count."',`movie_stime`=".date('YmdHmi',time())." WHERE id=".$var['id'];
                        $this->model->query($sql_update);
                    }
                }
                $sql="UPDATE `h_moviemenu` SET `menu_name`='".$menu_nameEdit."',`morder`='".$morder."',`content`='".$menu_name."' WHERE id=".$id;

                //自动分发分类修改任务
                $row_hotel = $this->model->query("SELECT * FROM `h_hotels` WHERE rstate<2");
                $sql_dis="INSERT INTO `h_distribute`(`hotelid`, `hotelname`, `movieid`, `moviename`, `state`, `content`) VALUES ";
                $sql_str='';
                foreach($row_hotel as $var){
                    $sql_str=$sql_str."('{$var['id']}','{$var['hotel']}','{$id}','{$menu_name}',21,'{$menu_nameEdit}'),";
                }
                $sql_str=substr($sql_str,0,-1);
                $sql_c=$sql_dis.$sql_str;
                $this->model->query($sql_c);
            }else{
                $sql_movie="SELECT id,movie_content FROM `h_movies` WHERE movie_content like '%".$menu_name."%' ";
                $row_movie=$this->model->query($sql_movie);
                if($row_movie){
                    foreach($row_movie as $var){
                        $menu_name_menu=$menu_name.'/'.$morderPer;
                        $menu_nameEdit=$menu_name.'/'.$morder;
                        $new_count=str_replace($menu_name_menu,$menu_nameEdit,$var['movie_content']);
                        $sql_update="UPDATE `h_movies` SET `movie_content`='".$new_count."',`movie_stime`=".date('YmdHmi',time())." WHERE id=".$var['id'];
                        $this->model->query($sql_update);
                    }
                }
                $sql="UPDATE `h_moviemenu` SET `morder`='".$morder."' WHERE id=".$id;
            }

            $this->addStaffLog('修改影库','修改影库：'.$menu_name,'classify');
            //   $this->model->query($sql);
        }else {
            $row=$this->model->query("SELECT max(morder) as morder FROM `h_moviemenu` where morder!= 100");
            if($row){
                $morder2=$row[0]['morder']+1;
            }
            if(!$morder){
                $morder=$morder2;
            }
            $sql="INSERT INTO `h_moviemenu`( `menu_name`, `morder`) VALUES ('{$menu_name}','{$morder}')";
            $this->addStaffLog('添加影库','添加影库：'.$menu_name,'classify');
        }
        unset($row_movie);
        unset($row_hotel);
        unset($row);
        $this->model->query($sql);
        $this->redirect(__APP__."/admin/dyfl");
    }

    //电影分类删除
    public function delallmoviemenu(){
        $json ='{';
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $name='';
        foreach ($strArr as $val){
            $sqls="SELECT * FROM `h_moviemenu` WHERE id=".$val;
            $rows = $this->model->query($sqls);

            $sqln="select count(*) as num from  h_movies where movie_state<2 and movie_content like '%".$rows[0]['menu_name']."%'";
            $listn  =   $this->model->query($sqln);
            $num=$listn[0]['num'];
            if($num){
                $json ='{"msg":"3","info":"'.$rows[0]['menu_name'].'分类下电影数量不为零，请先处理该分类下电影"}';
                echo $json;
                exit;
                //    $this->error($rows[0]['menu_name'].'分类下电影数量不为零，请先处理该分类下电影');
            }
            $name=$name.$rows[0]['menu_name'].'、';
            $sql = "delete from  h_moviemenu where id=".$val;
            $row = $this->model->query($sql);

            //自动分发分类修改任务
            $row_hotel = $this->model->query("SELECT * FROM `h_hotels` WHERE rstate<2");
            $sql_dis="INSERT INTO `h_distribute`(`hotelid`, `hotelname`, `movieid`, `moviename`, `state`, `content`) VALUES ";
            $sql_str='';
            foreach($row_hotel as $var){
                $sql_str=$sql_str."('{$var['id']}','{$var['hotel']}','{$val}','{$rows[0]['menu_name']}',21,'delete'),";
            }
            $sql_str=substr($sql_str,0,-1);
            $sql_c=$sql_dis.$sql_str;
            $this->model->query($sql_c);

        }
        $this->addStaffLog('删除影库','删除影库：'.$name,'classify');
        unset($rows);
        unset($listn);
        unset($row_hotel);
        $json ='{"msg":"1"}';
        echo $json;
        exit;
    }
    //电影排序修改按钮
    public function edit_order(){
        $flag= $_POST['flag'];
        $id= $_POST['id'];
        $row=$this->model->query("SELECT  morder FROM `h_moviemenu` where id =".$id);
        $morder=$row[0]['morder'];
        if($flag=='down'){
            $morder2=$morder+1;
        }else{
            $morder2=$morder-1;
        }
        $this->model->query("UPDATE `h_moviemenu` SET `morder`=".$morder." WHERE morder=".$morder2);
        $this->model->query("UPDATE `h_moviemenu` SET `morder`=".$morder2." WHERE id=".$id);
        $json ='{';
        $json .='"msg":"1"}';
        unset($row);
        echo $json;
        exit;
    }
    //选择电影
    public function catmovie(){
        $json ='{';
        $movie_sou = $_POST['arr'];

        $con_movie='';
        if($movie_sou){
            $con_movie="where movie_state<2 and movie_content	like '%".$movie_sou."%' ";
        }
        $sql="SELECT * FROM `h_movies` ".$con_movie." order by movie_stime,morder desc";
        $row = $this->model->query($sql);
        $this->assign("moviesArr",$row);
        $json_row=json_encode($row);
        $json .='"msg":"1","moviesArr":'.$json_row.'}';
        unset($row);
        echo $json;
        exit;
    }

    //分类显示电影
    public function showdetail(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $con="where movie_state<2 ";
        $filmname= $_GET['filmname'];
        if($filmname){
            $con =$con."  and movie_name like '%".$filmname."%' ";
        }
        $filmnemu= $_GET['menu'];
        if($filmnemu){
            $con =$con." and  movie_content like '%".$filmnemu."%' ";
        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $sql = "select count(*) as zs from h_movies ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select * from h_movies   ".$con."  order by id desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("moviesArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }
        $sql = "SELECT * FROM `h_moviemenu` WHERE menu_name='".$filmnemu."'";
        $list  =   $this->model->query($sql);
        if ($list){
            $filmnemu=$filmnemu.'/'.$list[0]['morder'];
        }
        unset($row);
        unset($list);
        $this->assign('filmnemu',$filmnemu);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dyfl']);
        $this->display("admin/showdetail");
    }

    public function detail_addmovie(){
        $movie_sou = $_POST['arr'];
        $menu = $_POST['menu'];
        //  var_dump($movie_sou);
        $ids =  substr($movie_sou, 0, -1);
        $strArr=explode('%',$ids);
        $movie_nameadd='';
        foreach ($strArr as $val){
            //    $movie_content=$val;
            $movieArry=explode('++',$val);
            $movie_id=$movieArry[0];
            $movie_content=$movieArry[1];
            $movie_name=$movieArry[2].'、';
            $movie_contentArry=explode('#',$movie_content);
            $movie_menu=$movie_contentArry[0];
            $r=stristr($movie_menu,$menu);
            if(!$r){
                $movie_menu=$movie_menu.$menu.',';
                $movie_contentnew=$movie_menu.stristr($movie_content,"#");
                $sql="UPDATE `h_movies` SET `movie_content`='{$movie_contentnew}' WHERE id=".$movie_id;
                $list  =   $this->model->query($sql);
                $movie_nameadd=$movie_nameadd.$movie_name;
            }
            //   file_put_contents("test.txt",$movie_contentnew.'---------',FILE_APPEND);
        }
        $menuArry=explode('/',$menu);
        $this->addStaffLog('添加影库中电影','添加影库 '.$menuArry[0].'中的电影：'.$movie_nameadd,'classify');
        //    file_put_contents("test.txt",$movie_sou.'-----'.$menu."\r\n",FILE_APPEND);
        $json ='{"msg":"1"}';
        echo $json;
        exit;
    }

    public function detail_delmovie(){
        $movie_sou = $_POST['arr'];
        $menu = $_POST['menu'];
        $menu_order=explode('/',$menu);
        $menu_name=$menu_order[0];
        $ids =  substr($movie_sou, 0, -1);
        $strArr=explode(',',$ids);
        $movie_name='';
        foreach ($strArr as $val){
            $sql="SELECT * FROM `h_movies` WHERE id=".$val;
            $list  =   $this->model->query($sql);
            $movie_content=$list[0]['movie_content'];
            $movie_name=$movie_name.$list[0]['movie_name'].'、';
            $movie_contentArry=explode('#',$movie_content);
            $movie_menu=$movie_contentArry[0];
            $movie_menuArry=explode(',',substr($movie_menu,0,-1));
            $count=count($movie_menuArry);
            if($count==1){
                $movie_menunew='无所属分类/100';
            }else{
                $movie_menunew='';
                foreach($movie_menuArry as $var){
                    $find=strstr($var,$menu_name);
                    if(!$find){
                        $movie_menunew=$movie_menunew.$var.',';
                    }
                }
            }
            $movie_contentnew=$movie_menunew.stristr($movie_content,"#");
            //    file_put_contents("test.txt",$movie_contentnew.'---------',FILE_APPEND);
            $sql="UPDATE `h_movies` SET `movie_content`='{$movie_contentnew}' WHERE id=".$val;
            $list  =   $this->model->query($sql);
        }
        $this->addStaffLog('删除影库中电影','删除影库 '.$menu_name.'中的电影：'.$movie_name,'classify');
        $json ='{"msg":"1"}';
        unset($strArr);
        unset($list);
        echo $json;
        exit;
    }

    public function operationlog(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $con="where id>0 ";
        $type= $_GET['type'];
        if($type){
            $con =$con."  and role= '".$type."'";
        }
        $username=$_SESSION['manage_groupid'];
        if($username){
            $uname= $_SESSION['manage_uname'];
            $con =$con." and  uname ='".$uname."' ";
        }
        $stime= $_GET['stime'];
        if($stime){
            $con =$con." and  time >= '".$stime."' ";
        }
        $etime= $_GET['etime'];
        if($etime){
            $con =$con." and  time <='".$etime."' ";
        }

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $sql = "select count(*) as zs from h_stafflog ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select * from h_stafflog  ".$con."  order by id desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("moviesArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }

        $this->assign('type',$type);
        switch ($type){
            case task:
                $left='admin_ffgl';
                $temp='admin';
                break;
            case movie:
                $left='admin_dygl';
                $temp='admin';
                break;
            case classify:
                $left='admin_dyfl';
                $temp='admin';
                break;
            case hotel:
                $left='admin_hotelName';
                $temp='admin';
                break;
            case permission:
                $left='system_permission';
                $temp='system';
                break;
            case user:
                $left='system_index';
                $temp='system';
                break;
            case upload:
                $left='admin_ccgl';
                $temp='admin';
                break;
            case m1905:
                $left='admin_m1905';
                $temp='admin';
                break;
            case hotelGroup:
                $left='admin_hotelGroup';
                $temp='admin';
                break;
            case hotelArea:
                $left='admin_hotelArea';
                $temp='admin';
                break;
            case singlepay:
                $left='admin_singlepay';
                $temp='admin';
                break;
            case payName:
                $left='admin_allname';
                $temp='admin';
                break;
            case allpay:
                $left='admin_allpay';
                $temp='admin';
                break;
        }
        unset($row);
        unset($list);
        $this->assign("left",$left);
        $this->display($temp."/stafflog");
    }

    //酒店名管理
    public function hotelName(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $name = $_GET['name'];
        if($name){
            $condition = "hotel like '%".$name."%'";
            $con=" where hotel like '%".$name."%' ";
        }

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=10;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);
        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $count=$this->model->table('h_hotels')->where($condition)->count();
        $sql = "select * from h_hotels ".$con." order by id ".$limitStr ;

        $list  =   $this->model->query($sql);
        $this->assign('count',$count);
        if($listRows>=$count){
            $this->assign('page','');
        }else{
            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
        }
        if(count($list)){
            $this->assign("roomArr",$list);
        }
//        //酒店分组
//        $rowhotelGroup = $this->model->query("select id,groupname from h_hotels_group where 1");
//        if($rowhotelGroup){
//            $this->assign("hotelGroup",$rowhotelGroup);
//        }
//
//        //城市设置
//
//        $sql1 = "select * from h_citys where depth=1";
//        $list1 = $this->model->query($sql1);
//        $this->assign("list1",$list1);
//        $sql2 = "select * from h_citys where parent='".$list1[0]['assign']."'";
//        $list2 = $this->model->query($sql2);
//        $this->assign("list2",$list2);
//        $sql3 = "select * from h_citys where parent='".$list2[0]['assign']."'";
//        $list3 = $this->model->query($sql3);
//        $this->assign("list3",$list3);
//        unset($row);
//        unset($list);
//        unset($list1);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['hotelName']);
        $this->display("admin/hotelName");
    }

    public function getcity2(){
        $code = $_POST['code'];
        $sql = "select * from h_citys where parent='".$code."'";
        $list = $this->model->query($sql);
        $city = "";
        foreach ($list as $l){
            $city .= "<option value='".$l['assign']."'>{$l['cityName']}</option>";
        }
        echo $city;
        unset($list);

        exit;
    }

    //酒店删除
    public function delallhotel(){
        $msg = 1;

        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $username='';
        foreach ($strArr as $val){
            $sql = "select * from h_hotels where  id=".$val;
            $row = $this->model->query($sql);
            if ($row){
                $username=$username.$row[0]['hotel'].'、';
                $sql = "delete from h_hotels where id=".$val ;
                $row = $this->model->query($sql);
            }else{
                $msg = 2;
            }
        }
        $this->addStaffLog('删除酒店','删除酒店：'.$username,'hotel');
        $json ='{"msg":"'.$row.'"}';
        unset($row);
        echo $json;
        exit;
    }


    public function addhotel(){
        $hotel = $_POST['hotel'];
        $hotelIP = $_POST['hotelIP'];
        $hotelName = $_POST['hotelName'];
        $citycode = $_POST['x'];
		$english_name = $_POST['english_name'];
		$hotel_room = $_POST['hotel_room'];
		$XScount =  $_POST['XScount'];
        $TVcount =  $_POST['TVcount'];
        $PCcount =  $_POST['PCcount'];
		$starlevel = $_POST['starlevel'];
		$hotelGroup = $_POST['hotelGroup'];
		$operationStatus =  $_POST['operationStatus'];
        $hotel_key =  $_POST['hotel_key'];
		$hotel_server_key =  $_POST['hotel_server_key'];
		$hotel_server_ip =  $_POST['hotel_server_ip'];
        $hotel_use_state =  $_POST['hotel_use_state'];
        $Remarks =  $_POST['Remarks'];
        $addtime =  date('Y-m-d H:i:s',time());
        $address = $_POST['realaddr'];
        $lat = round($_POST['Lat']*100000000);
        $lng = round($_POST['Lng']*100000000);
        $id = $_POST['id'];

        $hotel_suburb =  $_POST['hotel_suburb'];
        $hotel_brand =  $_POST['hotel_brand'];
        $addrDetial = $_POST['addrDetial'];
        $hotel_english_location = $_POST['hotel_english_location'];
		$hotel_english_location = $_POST['hotel_english_location'];
		$hotel_try_start = $_POST['hotel_try_start'];
		$hotel_try_end = $_POST['hotel_try_end'];
		$contractStartTime = $_POST['contractStartTime'];
		$contractEndTime = $_POST['contractEndTime'];
		$contractNo = $_POST['contractNo'];
		$hotel_phone = $_POST['hotel_phone'];
		$hotel_info_manage_linkman = $_POST['hotel_info_manage_linkman'];
		$hotel_info_manage_linkman_phone = $_POST['hotel_info_manage_linkman_phone'];
        $hotel_info_manage_company = $_POST['hotel_info_manage_company'];
		$hotel_info_manage_location = $_POST['hotel_info_manage_location'];
		$hotel_info_manage_boss = $_POST['hotel_info_manage_boss'];
		$hotel_info_manage_boss_phone = $_POST['hotel_info_manage_boss_phone'];
		$hotel_info_hotel_sell_boss = $_POST['hotel_info_hotel_sell_boss'];
		$hotel_info_hotel_sell_boss_phone = $_POST['hotel_info_hotel_sell_boss_phone'];
		$hotel_info_hotel_engineer_boss = $_POST['hotel_info_hotel_engineer_boss'];
		$hotel_info_hotel_engineer_boss_phone = $_POST['hotel_info_hotel_engineer_boss_phone'];
		$hotel_info_hotel_contracter = $_POST['hotel_info_hotel_contracter'];
		$hotel_info_hotel_contracter_phone = $_POST['hotel_info_hotel_contracter_phone'];
		$hotel_info_hotel_clientele = $_POST['hotel_info_hotel_clientele'];
		$hotel_info_hotel_develop = $_POST['hotel_info_hotel_develop'];
		$hotel_info_hotel_develop_phone = $_POST['hotel_info_hotel_develop_phone'];

        if(empty($hotel)){
            $this->error('酒店名不能为空！');
        }
        if(empty($hotelName)){
            $this->error('酒店程序名不能为空！');
        }
		if(empty($hotel_room)){
            $this->error('客房数量不能为空！');
        }
//		if(empty($hotel_try_start)){
//            $this->error('试用开始时间不能为空！');
//        }
//		if(empty($hotel_try_end)){
//            $this->error('试用结束时间不能为空！');
//        }
//		if(empty($contractStartTime)){
//            $this->error('合同开始时间不能为空！');
//        }
//		if(empty($contractEndTime)){
//            $this->error('合同结束时间不能为空！');
//        }
		if(empty($hotel_server_key)){
            $this->error('tlk服务器Key不能为空！');
        }else{
            $con='';
		    if($id){
		        $con=' and id!='.$id;
            }
            $row = $this->model->query("select * from h_hotels where hotel_server_key ='".$hotel_server_key."'" .$con);
		    if($row){
                $this->error('tlk服务器Key：'.$hotel_server_key.'已存在，请查重！');
            }
        }
		if(empty($hotel_server_ip)){
            $this->error('服务器IP地址不能为空！');
        }
        $adminId = $_SESSION['manage_uid'];
        $row = $this->model->query("select * from h_hotels where id ='".$id."'");
        if($row){
            $sql="UPDATE `h_hotels` SET `hotelName`='{$hotelName}',`hotel`='{$hotel}',`english_name`='{$english_name}',`citycode`='{$citycode}',`starlevel`='{$starlevel}',`groupId`='{$hotelGroup}',`operationStatus`='{$operationStatus}',`demand`='{$Remarks}',`ipaddr`='{$hotelIP}',`clientNo`='{$XScount}',`clientNoPc`='{$PCcount}',`clientNoTv`='{$TVcount}',`lat`='{$lat}',`lng`='{$lng}',`address`='{$address}',`hotel_key`='{$hotel_key}',`hotel_room`='{$hotel_room}',`hotel_server_key`='{$hotel_server_key}',`hotel_server_ip`='{$hotel_server_ip}',`hotel_use_state`='{$hotel_use_state}',`synUpdateState`=0 WHERE id='{$id}'";
            $row = $this->model->query($sql);
            $this->addStaffLog('修改酒店信息','修改酒店信息：'.$hotel,'hotel');
            $hotelId = $id;
        }else {
            $hotel_contract = md5(time());
            $sql="INSERT INTO `h_hotels`( `hotelName`, `hotel`, `english_name`, `citycode`, `starlevel`, `groupId`, `operationStatus`, `addtime`, `addadminId`, `rstate`, `vpnstate`, `demand`, `ipaddr`,  `cpu`, `stime`, `clientNo`, `clientNoPc`, `clientNoTv`, `lat`, `lng`, `address`,  `hotel_key`, `hotel_contract`, `hotel_room`, `hotel_server_key`, `hotel_server_ip`, `hotel_use_state`, `synUpdateState`) VALUES
('{$hotelName}','{$hotel}','{$english_name}','{$citycode}','{$starlevel}','{$hotelGroup}','{$operationStatus}','{$addtime}','{$adminId}',0,0,'{$Remarks}','{$hotelIP}','','','{$XScount}','{$PCcount}','{$TVcount}','{$lat}','{$lng}','{$address}','{$hotel_key}','{$hotel_contract}','{$hotel_room}','{$hotel_server_key}','{$hotel_server_ip}','{$hotel_use_state}',0)";
            $row = $this->model->query($sql);
            $hotelId =  $this->model->insert_id();
            $this->addStaffLog('新增酒店信息','新增酒店信息：'.$hotel,'hotel');
        }

        foreach($_POST as $k=>$v){
            $dateNow= date('Y-m-d',time());
            switch($k){
                case 'hotel':
                case 'hotelIP':
                case 'hotelName':
                case 'x':
                case 'english_name':
                case 'hotel_room':
                case 'XScount':
                case 'TVcount':
                case 'PCcount':
                case 'starlevel':
                case 'hotelGroup':
                case 'operationStatus':
                case 'hotel_key':
                case 'hotel_server_key':
                case 'hotel_server_ip':
                case 'hotel_use_state':
                case 'Remarks':
                case 'realaddr':
                case 'Lat':
                case 'Lng':
                    break;
                default :
                    $rowAttrId = $this->model->query("SELECT id FROM `h_hotels_attribute` WHERE `attributeFlag`='".$k."'");
                    if($rowAttrId){
                        $attrId= $rowAttrId[0]['id'];
                        $sqlContent="SELECT ii.content,ii.id FROM  h_hotelsid_attributeid ii  WHERE ii.hotelId=".$hotelId ." and ii.attributeId=".$attrId ;
                        $rowContent = $this->model->query($sqlContent);
                        if($rowContent){
                            $contentPre=$rowContent[0]['content'];
                            if($contentPre!=$v){
                                $contentId=$rowContent[0]['id'];
                                $sql="UPDATE `h_hotelsid_attributeid` SET   `content`='{$v}',`editTime`='{$dateNow}',`adminId`='{$adminId}' WHERE `id`=".$contentId;
                                $rowresult=$this->model->query($sql);
                            }
                        }else{
                            $rowresult=$this->model->query("INSERT INTO `h_hotelsid_attributeid`( `hotelId`, `attributeId`, `content`, `editTime`, `adminId`) VALUES ('{$hotelId}','{$attrId}','{$v}','{$dateNow}','{$adminId}')");
                        }
                    }
                    break;
            }
        }

        if($row){
            unset($row);
            $this->error('更新成功！');
        }else{
            unset($row);
            $this->error('更新失败！');
        }
    }

    public function getHotelInfo(){
        $id= $_POST['id'];

        $sqlContent="SELECT ha.attributeFlag,ii.content FROM `h_hotels_attribute`  ha  left join h_hotelsid_attributeid ii on ha.id=ii.attributeid WHERE ii.hotelId=".$id;
        $rowContent = $this->model->query($sqlContent);
        if($rowContent){
            foreach( $rowContent as $c){
                $arryProcess[$c['attributeFlag']] = $c['content'];
            }
            echo json_encode($arryProcess);
        }
    }


//电影导入
    public function movieimport(){
        require(CP_PATH.'ext/PHPExcel.php');
        if($_POST){
            // $time = time();
//var_dump($_FILES);
            $filename='public/temp/1.xls';

            $error = array('请选择上传数据包！','读取数据包失败！','请检查上传数据包,下列位置数据不能为空:',
                '插入顶级分类数据失败！','二级分类插入失败！','插入电影失败！',' 数据包格式有问题,请确认下上传XLS格式数据包！','电影路径有问题，请检查数据包格式！','内容不存在','名称不能有空格');

            if (!$_FILES[movefile][name]){
                $this->assign("error",$error[0]);
                $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                $this->display("admin/movieimport");
                exit;
//            }elseif($_FILES[movefile][type]!='application/vnd.ms-excel'){
//                $this->assign("error",$error[6]);
            }else {

                $xls_error  = '';
                move_uploaded_file($_FILES["movefile"]["tmp_name"], $filename);

                $PHPReader = new PHPExcel_Reader_Excel2007();
                if(!$PHPReader->canRead($filename)){
                    $PHPReader = new PHPExcel_Reader_Excel5();
                    if(!$PHPReader->canRead($filename)){
                        $this->assign("error",$error[1]);
                    }
                }

                $PHPExcel = $PHPReader->load($filename);
                $currentSheet = $PHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();
                $allRow = $currentSheet->getHighestRow();
                for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){
                    for($colIndex='A';$colIndex<='W';$colIndex++){
                        $addr = $colIndex.$rowIndex;
                        $cell = $currentSheet->getCell($addr)->getValue();
                        if($cell instanceof PHPExcel_RichText)
                            $cell = $cell->__toString();
                        if($colIndex!='C'and $colIndex!='S' and $colIndex!='T' and$colIndex!='U' and$colIndex!='V' and$colIndex!='W' and $cell==""){
                            $xls_error = '1';
                            $error_desc .= $addr.',';
                        }

                        if($colIndex=='A'){
                            $movie_true_path = $currentSheet->getCell('A'.$rowIndex)->getValue();
                            $last_s=substr($movie_true_path,-1,1);
                            if($last_s!='/'){
                                $this->assign("error",$error[7].'--:'.$movie_true_path);
                                $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                                $this->display("admin/movieimport");
                                exit;
                            }
                        }
                        $movie_true_path = $currentSheet->getCell('A'.$rowIndex)->getValue();
                        //    $key='travelink:!@#$qwASDF';
                        //    $movie_true_path=str_replace('http://',"http://'".$key."'@",$movie_excel_path);
                        $movie_true_name = $currentSheet->getCell('B'.$rowIndex)->getValue();
                        $movie_true_name_check=strstr($movie_true_name," ") ;
                        if($movie_true_name_check){
                            $this->assign("error",$movie_true_name.$error[9]);
                            $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                            $this->display("admin/movieimport");
                            exit;
                        }
                        $movie_poster = $currentSheet->getCell('C'.$rowIndex)->getValue();
                        $movie_poster_check=strstr($movie_poster," ") ;
                        if($movie_poster_check){
                            $this->assign("error",$movie_poster.$error[9]);
                            $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                            $this->display("admin/movieimport");
                            exit;
                        }
                        $movie_thumb = $currentSheet->getCell('D'.$rowIndex)->getValue();
                        $movie_thumb_check=strstr($movie_thumb," ") ;
                        if($movie_thumb_check){
                            $this->assign("error",$movie_thumb.$error[9]);
                            $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                            $this->display("admin/movieimport");
                            exit;
                        }
                        $movie_url=$movie_true_path.$movie_true_name;
                        $exists_movie_url =$this-> check_remote_file_exists($movie_url);
                        if (!$exists_movie_url) {
                            $this->assign("error",$movie_url.$error[8]);
                            $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                            $this->display("admin/movieimport");
                            exit;
                        }

                        if($movie_poster){
                            $poster_url=$movie_true_path.$movie_poster;
                            $exists_poster_url =$this-> check_remote_file_exists($poster_url);
                            if (!$exists_poster_url) {
                                $this->assign("error",$poster_url.$error[8]);
                                $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                                $this->display("admin/movieimport");
                                exit;
                            }
                        }
                        $thumb_url=$movie_true_path.$movie_thumb;
                        $exists_thumb_url =$this-> check_remote_file_exists($thumb_url);
                        if (!$exists_thumb_url) {
                            $this->assign("error",$thumb_url.$error[8]);
                            $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                            $this->display("admin/movieimport");
                            exit;
                        }
                    }
                }

                if($xls_error){
                    $this->assign("error",$error[2].$error_desc);
                    $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                    $this->display("admin/movieimport");
                    exit;
                }else{

                    //目录
                    $sql_menu="SELECT * FROM `h_moviemenu` WHERE 1";
                    $sql_menu_row = $this->model->query($sql_menu);
                    if($sql_menu_row){
                        $menu_sql_arry=array();
                        foreach($sql_menu_row as $var){
                            $menu_sql_arry[]=$var['menu_name'].'/'.$var['morder'];
                        }
                    }

                    $import_movie_name = '';
                    $import_movie_name_edit = '';
                    $err='';
                    $import_movie_topclass = '';
                    $import_movie_secclass = '';
                    for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){
                        $movie_true_path = $currentSheet->getCell('A'.$rowIndex)->getValue();
                        $movie_true_name   = $currentSheet->getCell('B'.$rowIndex)->getValue();
                        $movie_poster   = $currentSheet->getCell('C'.$rowIndex)->getValue();
                        $movie_thumb = $currentSheet->getCell('D'.$rowIndex)->getValue();

                        $movie_name = $currentSheet->getCell('E'.$rowIndex)->getValue();
                        $movie_secondclass_name = $currentSheet->getCell('F'.$rowIndex)->getValue();
                        $movie_topclass_name = $currentSheet->getCell('G'.$rowIndex)->getValue();

                        //简介@导演@主演@热度@时长@地区@上映时间@标签类型@评分@播放次数@分辨率@电影排序
                        $movie_details = $currentSheet->getCell('H'.$rowIndex)->getValue();
                        $movie_director   = $currentSheet->getCell('I'.$rowIndex)->getValue();
                        $movie_actor   = $currentSheet->getCell('J'.$rowIndex)->getValue();
                        $movie_hot = $currentSheet->getCell('K'.$rowIndex)->getValue();
                        $movie_length = $currentSheet->getCell('L'.$rowIndex)->getValue();
                        $movie_area = $currentSheet->getCell('M'.$rowIndex)->getValue();
                        $movie_showtime = $currentSheet->getCell('N'.$rowIndex)->getValue();
                        $movie_label   = $currentSheet->getCell('O'.$rowIndex)->getValue();
                        $movie_score   = $currentSheet->getCell('P'.$rowIndex)->getValue();
                        $movie_playtimes = $currentSheet->getCell('Q'.$rowIndex)->getValue();
                        $movie_resolution = $currentSheet->getCell('R'.$rowIndex)->getValue();

                        $movie_ss = $currentSheet->getCell('S'.$rowIndex)->getValue();
                        $movie_price = $currentSheet->getCell('T'.$rowIndex)->getValue();
                        $movie_true_trailer = $currentSheet->getCell('U'.$rowIndex)->getValue();
                        $movie_Issuer = $currentSheet->getCell('V'.$rowIndex)->getValue();
                        $movie_Order = $currentSheet->getCell('W'.$rowIndex)->getValue();

                        if($movie_true_path instanceof PHPExcel_RichText)
                            $movie_true_path = $movie_true_path->__toString();
                        if($movie_true_name instanceof PHPExcel_RichText)
                            $movie_true_name = $movie_true_name->__toString();
                        if($movie_poster instanceof PHPExcel_RichText)
                            $movie_poster = $movie_poster->__toString();
                        if($movie_thumb instanceof PHPExcel_RichText)
                            $movie_thumb = $movie_thumb->__toString();
                        if($movie_name instanceof PHPExcel_RichText)
                            $movie_name = $movie_name->__toString();
                        if($movie_secondclass_name instanceof PHPExcel_RichText)
                            $movie_secondclass_name = $movie_secondclass_name->__toString();
                        if($movie_topclass_name instanceof PHPExcel_RichText)
                            $movie_topclass_name = $movie_topclass_name->__toString();

                        if($movie_details ){
                            $movie_details=str_replace(array("\r\n", "\r", "\n",'"'), '', $movie_details);
                        }

                        if($movie_director instanceof PHPExcel_RichText)
                            $movie_director = $movie_director->__toString();
                        if($movie_actor instanceof PHPExcel_RichText)
                            $movie_actor = $movie_actor->__toString();
                        if($movie_hot instanceof PHPExcel_RichText)
                            $movie_hot = $movie_hot->__toString();
                        if($movie_length instanceof PHPExcel_RichText)
                            $movie_length = $movie_length->__toString();
                        if($movie_area instanceof PHPExcel_RichText)
                            $movie_area = $movie_area->__toString();
//                        if($movie_showtime)
//                            $movie_showtime = gmdate("Y年m月", PHPExcel_Shared_Date::ExcelToPHP($movie_showtime));
                        if($movie_showtime instanceof PHPExcel_RichText)
                            $movie_showtime = $movie_showtime->__toString();
                        if($movie_label instanceof PHPExcel_RichText)
                            $movie_label = $movie_label->__toString();
                        if($movie_score instanceof PHPExcel_RichText)
                            $movie_score = $movie_score->__toString();
                        if($movie_playtimes instanceof PHPExcel_RichText)
                            $movie_playtimes = $movie_playtimes->__toString();
                        if($movie_resolution instanceof PHPExcel_RichText)
                            $movie_resolution = $movie_resolution->__toString();
                        if($movie_ss instanceof PHPExcel_RichText)
                            $movie_ss = $movie_ss->__toString();
                        if($movie_price instanceof PHPExcel_RichText)
                            $movie_price = $movie_price->__toString();
                        if($movie_true_trailer instanceof PHPExcel_RichText)
                            $movie_true_trailer = $movie_true_trailer->__toString();
                        if($movie_Issuer instanceof PHPExcel_RichText)
                            $movie_Issuer = $movie_Issuer->__toString();
                        if($movie_Order instanceof PHPExcel_RichText)
                            $movie_Order = $movie_Order->__toString();

                        $movie_Order=$movie_Order?$movie_Order:0;

                        $movie_ss=str_replace("'","’",$movie_ss);
                        $movie_director=str_replace("'","’",$movie_director);
                        $movie_actor=str_replace("'","’",$movie_actor);

                        $movie_price=$movie_price?$movie_price:0;
                        $movie_name_array = explode("|",$movie_name);
                        $movie_secondclass_name_array = explode("|",$movie_secondclass_name);

                        $movie_menu='';

                        foreach($movie_secondclass_name_array as $var_secondclass_nam){
                            foreach($menu_sql_arry as $var_menu_sql){
                                $pos =strstr($var_menu_sql,$var_secondclass_nam);
                                if($pos){
                                    $movie_menu=$movie_menu.$var_menu_sql.',';
                                }
                            }
                            $pos2 =strstr($movie_menu,$var_secondclass_nam);
                            if(!$pos2){
//                                $this->assign("error",$error[1]);
                                $err=$err.$var_secondclass_nam.'/';
                                //  $movie_menu=$movie_menu.$var_secondclass_nam.'/0,';
                            }
                        }
                        if($err){
                            $this->assign("error",$error[4].$err);
                            $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                            $this->display("admin/movieimport");
                            exit;
                        }else{
                            $movie_content=$movie_menu.'#'.$movie_price.'#'.$movie_details.'@'.$movie_director.'@'.$movie_actor.'@'.$movie_hot.'@'.$movie_length.'@'.$movie_area.'@'.$movie_showtime.'@'.$movie_label.'@'.$movie_score.'@'.$movie_playtimes.'@'.$movie_resolution.'@'.$movie_Order.'#1#'.$movie_ss;
                            $movie_content=str_replace("'","’",$movie_content);
                            $movie_addr=$movie_true_path.$movie_true_name;
                            $movie_trailer=$movie_true_path.$movie_true_trailer;
                            $movie_pic=$movie_true_path.$movie_thumb;
                            $movie_post=$movie_true_path.$movie_poster;

                            //处理电影
                            $time=time();
                            $movie_sel_sql = "SELECT * FROM `h_movies` WHERE movie_name = '$movie_name_array[0]'";
                            $movie_sel_row = $this->model->query($movie_sel_sql);
                            if($movie_sel_row){
                                $moveid = $movie_sel_row[0]['id'];
                                $movie_edit_sql="UPDATE `h_movies` SET `movie_name`='{$movie_name}',`movie_addr`='{$movie_addr}',`movie_trailer`='{$movie_trailer}',`movie_pic`='{$movie_pic}',`movie_post`='{$movie_post}',`movie_content`='{$movie_content}', `Issuer`='{$movie_Issuer}', `morder`='{$rowIndex}' WHERE id=".$moveid;
                                $this->addStaffLog('修改电影','修改电影：'.$movie_name,'movie');
                                $this->model->query($movie_edit_sql);
                                $import_movie_name_edit .= $movie_name_array[0].',';
                            }else{
                                $movie_add_sql="INSERT INTO `h_movies`( `movie_name`, `movie_addr`,`movie_trailer`, `movie_pic`, `movie_post`, `movie_content`,  `movie_stime`, `Issuer`, `morder`) VALUES ('{$movie_name}','{$movie_addr}','{$movie_trailer}','{$movie_pic}','{$movie_post}','{$movie_content}','{$time}','{$movie_Issuer}','{$rowIndex}')";
                                $this->addStaffLog('添加电影','添加电影：'.$movie_name,'movie');
                                $this->model->query($movie_add_sql);
                                $import_movie_name .= $movie_name_array[0].',';
                            }
                        }
                    }

                    unset($sql_menu_row);
                    unset($currentSheet);
                    unset($movie_sel_row);
                    $this->assign("success",'数据处理成功！<br/>新增电影:'.$import_movie_name.'<br/>修改电影:'.$import_movie_name_edit);
                    $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
                    $this->display("admin/movieimport");
                    exit;
                }
            }
        }
        unset($currentSheet);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['dygl']);
        $this->display("admin/movieimport");
    }

    public function check_remote_file_exists($url) {
        $curl = curl_init($url);
        //不取回数据
        curl_setopt($curl, CURLOPT_NOBODY, true);
        $username = 'travelink';
        $password = '!@#$qwASDF';
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        //    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
        //发送请求
        $result = curl_exec($curl);
        $found = false;
        if ($result !== false) {
            //检查http响应码是否为200
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if ($statusCode == 200) {
                $found = true;
            }
        }
        curl_close($curl);
        return $found;
    }

    //电影导出
    public function movieExport(){
        require(CP_PATH.'ext/PHPExcel.php');
        require(CP_PATH.'ext/PHPExcel/Writer/Excel5.php');
        require(CP_PATH.'ext/PHPExcel/Writer/Excel2007.php');
        error_reporting(E_ALL);
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array('memoryCacheSize'=>'16MB');
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
        $objPHPExcel = new PHPExcel();
        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("cj")
            ->setLastModifiedBy("cj")
            ->setTitle("数据EXCEL导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");

        // 表头
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '上级电影路径')
            ->setCellValue('B1', '电影物理名称')
            ->setCellValue('C1', '海报图片')
            ->setCellValue('D1', '缩略图')
            ->setCellValue('E1', '电影名')
            ->setCellValue('F1', '上级分类')
            ->setCellValue('G1', '顶级分类')
            ->setCellValue('H1', '简介')
            ->setCellValue('I1', '导演')
            ->setCellValue('J1', '主演')
            ->setCellValue('K1', '热度')
            ->setCellValue('L1', '时长(分钟)')
            ->setCellValue('M1', '地区')
            ->setCellValue('N1', '上映时间')
            ->setCellValue('O1', '标签类型')
            ->setCellValue('P1', '评分')
            ->setCellValue('Q1', '播放次数(次)')
            ->setCellValue('R1', '分辨率')
            ->setCellValue('S1', '搜索关键字')
            ->setCellValue('T1', '价格')
            ->setCellValue('U1', '预告片')
            ->setCellValue('V1', '发行方')
            ->setCellValue('W1', '排序');
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:W1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:W1')->getFill()->getStartColor()->setARGB("#0cedffb");
        $objPHPExcel->getActiveSheet()->getStyle('A1:W1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getRowDimension(1)->setRowHeight(35);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(15);
        $styleThinBlackBorderOutline = array(
            'borders' => array (
                'outline' => array (
                    'style' => PHPExcel_Style_Border::BORDER_THIN,  //设置border样式
                    //'style' => PHPExcel_Style_Border::BORDER_THICK, 另一种样式
                    'color' => array ('argb' => 'FF000000'),     //设置border颜色
                ),
            ),
        );
        for($i='A';$i<'X';$i++){
            $objPHPExcel->getActiveSheet()->getStyle($i.'1')->applyFromArray($styleThinBlackBorderOutline);
        }
        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        $movie_sel_sql = "SELECT * FROM `h_movies` WHERE movie_state<2 order by morder asc ";
        $data = $this->model->query($movie_sel_sql);

        foreach($data as $k => $v){
            $E= $v['movie_name'];
            $V=$v['Issuer'];
            $movie_addr=$v['movie_addr'];
            $movie_trailer=$v['movie_trailer'];
            $movie_pic=$v['movie_pic'];
            $movie_post=$v['movie_post'];
            $movie_content=$v['movie_content'];
//分类#价格#简介@导演@主演@热度@时长@地区@上映时间@标签类型@评分@播放次数@分辨率@电影排序#语言#搜索
            $A=str_replace(substr(strrchr($movie_addr,'/'),1),'',$movie_addr);
            $B=substr(strrchr($movie_addr,'/'),1);
            $C=substr(strrchr($movie_post,'/'),1);
            $D=substr(strrchr($movie_pic,'/'),1);
            $U=substr(strrchr($movie_trailer,'/'),1);
            if(!$U){
                $U='';
            }
            if(!$C){
                $C=0;
            }
            $G='高清影院';
            $Arry_movie_content=explode('#',$movie_content);
            $T=$Arry_movie_content[1];
            //上级分类
            $S=$Arry_movie_content[4];
            $menuStr=$Arry_movie_content[0];
            $menuArr=explode(',',substr($menuStr,0,-1));
            $menu='';
            foreach($menuArr as $var){
                $menu=$menu.strstr($var,'/',true).'|';
            }
            $F=substr($menu,0,-1);
            //电影信息属性
            $contentArr=explode('@',$Arry_movie_content[2]);
            $H=$contentArr[0];
            $I=$contentArr[1];
            $J=$contentArr[2];
            $K=$contentArr[3];
            $L=$contentArr[4];
            $M=$contentArr[5];
            $N=$contentArr[6];
            $O=$contentArr[7];
            $P=$contentArr[8];
            $Q=$contentArr[9];
            $R=$contentArr[10];
            $W=$contentArr[11]?$contentArr[11]:0;

            $num=$k+2;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$num, $A)
                ->setCellValue('B'.$num, $B)
                ->setCellValue('C'.$num, $C)
                ->setCellValue('D'.$num, $D)
                ->setCellValue('E'.$num, $E)
                ->setCellValue('F'.$num, $F)
                ->setCellValue('G'.$num, $G)
                ->setCellValue('H'.$num, $H)
                ->setCellValue('I'.$num, $I)
                ->setCellValue('J'.$num, $J)
                ->setCellValue('K'.$num, $K)
                ->setCellValue('L'.$num, $L)
                ->setCellValue('M'.$num, $M)
                ->setCellValue('N'.$num, $N)
                ->setCellValue('O'.$num, $O)
                ->setCellValue('P'.$num, $P)
                ->setCellValue('Q'.$num, $Q)
                ->setCellValue('R'.$num, $R)
                ->setCellValue('S'.$num, $S)
                ->setCellValue('T'.$num, $T)
                ->setCellValue('U'.$num, $U)
                ->setCellValue('V'.$num, $V)
                ->setCellValue('W'.$num, $W);

            for($i='A';$i<'X';$i++){
                $objPHPExcel->getActiveSheet()->getStyle($i.$num)->applyFromArray($styleThinBlackBorderOutline);
                $objPHPExcel->getActiveSheet()->getStyle($i.$num)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
            }
            $objPHPExcel->setActiveSheetIndex(0)->getRowDimension($num)->setRowHeight(35);
        }

        $objPHPExcel->getActiveSheet()->setTitle('movie');
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="电影导出_'.date("YmdHis").'.xls"');
        header('Cache-Control: max-age=0');
        ob_clean();//关键
        flush();//关键
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        unset($data);
        unset($objPHPExcel);
        exit;
    }

    //电影存储管理
    public function ccgl(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

//        $mname = $_GET['mname'];
//        $hname = $_GET['hname'];
        $con=" where id > 0 ";
//        if($hname){
//            $con =$con." and  hotelname like '%".$hname."%' ";
//        }
//        if($mname){
//            $con =$con." and  moviename like '%".$mname."%' ";
//        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        //  $sql="select d.*,m.movie_addr,m.movie_pic,h.ipaddr from h_distribute d left join h_hotels h on d.hotelid=h.id left join h_movies m on d.movieid=m.id ";
        $sql = "select count(*) as zs from h_canshu ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select * from h_canshu  ".$con."  order by id desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("contentArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }
        unset($row);
        unset($list);
        $this->assign("left",'admin_ccgl');
        $this->display("admin/ccgl");

    }
    public function ccglEdit()
    {
        $id=$_POST['id'];
        $x = $_POST['x'];
        if($id){
            $sql="UPDATE `h_canshu` SET `x`='".$x."' WHERE  id=".$id;
            $row = $this->model->query($sql);
            // $this->addStaffLog('修改存储任务','修改存储任务：'.$content,'task');
        }else{

        }
        unset($row);
        $this->redirect(__APP__."/admin/ccgl");
    }

    public function showContent(){
        $row_ip = $this->model->query( "SELECT * FROM `h_canshu` WHERE name='电影存储服务器ip'");
        $ftp_server=$row_ip[0]['x'];
        $row_dir = $this->model->query( "SELECT * FROM `h_canshu` WHERE name='电影存储服务器路径'");
        $ftp_dir=$row_dir[0]['x'];

        $ftp_user_name=$_SESSION['ftp_user_name'];
        $ftp_user_pass=$_SESSION['ftp_user_pass'];

        $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
        ftp_chdir($conn_id,$ftp_dir);
        //   ftp_cdup($conn_id);
        $ftp_list=ftp_nlist($conn_id,".");
        //    $this->assign("filesArr",$ftp_list);
        $json_row=json_encode($ftp_list);
        $json ='{"msg":"1","moviesArr":'.$json_row.'}';
        unset($row_ip);
        unset($row_dir);
        echo $json;
        exit;
    }

    public function showCheck(){
        $ftp_user_name=$_SESSION['ftp_user_name'];
        $ftp_user_pass=$_SESSION['ftp_user_pass'];

        if(!($ftp_user_name&&$ftp_user_pass)){
            $json ='{"msg":"2"}';
        }else{
            $json ='{"msg":"1"}';
        }
        echo $json;
        exit;
    }

    public function showLogin(){
        $ftp_user_name = $_POST['ftp_user_name'];
        $ftp_user_pass = $_POST['ftp_user_pass'];
        $row_ip = $this->model->query( "SELECT * FROM `h_canshu` WHERE name='电影存储服务器ip'");
        $ftp_server=$row_ip[0]['x'];
        $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
        if($login_result){
            $_SESSION['ftp_user_name']=$ftp_user_name;
            $_SESSION['ftp_user_pass']=$ftp_user_pass;
        }else{
            $this->error('登录失败');
        }
        unset($row_ip);

        $this->redirect(__APP__."/admin/ccgl");

    }

    public function upload_Movie(){
        if (empty($_FILES) === false) {
            //原文件名
            $file_name = $_FILES['Filedata']['name'];
            //   file_put_contents('file.txt','$file_name='.$file_name."\r\n",FILE_APPEND);
            //服务器上临时文件名
            $tmp_name = $_FILES['Filedata']['tmp_name'];
            //   file_put_contents('file.txt','$tmp_name='.$tmp_name."\r\n",FILE_APPEND);
            //文件大小
            //   $file_size = $_FILES['Filedata']['size'];
            //检查文件名
            $row_ip = $this->model->query( "SELECT * FROM `h_canshu` WHERE name='电影存储服务器ip'");
            $ftp_server=$row_ip[0]['x'];
            $row_dir = $this->model->query( "SELECT * FROM `h_canshu` WHERE name='电影存储服务器路径'");
            $ftp_dir=$row_dir[0]['x'];

            $ftp_user_name=$_SESSION['ftp_user_name'];
            $ftp_user_pass=$_SESSION['ftp_user_pass'];

            $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
            $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
            $file = $tmp_name;
            $remote_file =$ftp_dir.'/'. $file_name;

            if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
                $this->addStaffLog('上传文件','上传文件：'.$file_name.'  成功','upload');
                //  $this->error("文件:".$file_name."上传成功");
            } else {
                $this->addStaffLog('上传文件','上传文件：'.$file_name.'  失败','upload');
                //   $this->error( "上传失败");
            }
            ftp_close($conn_id);
        }
    }
    //电影上传管理
    public function addFile(){
        if (is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
            $row_ip = $this->model->query( "SELECT * FROM `h_canshu` WHERE name='电影存储服务器ip'");
            $ftp_server=$row_ip[0]['x'];
            $row_dir = $this->model->query( "SELECT * FROM `h_canshu` WHERE name='电影存储服务器路径'");
            $ftp_dir=$row_dir[0]['x'];

            $ftp_user_name=$_SESSION['ftp_user_name'];
            $ftp_user_pass=$_SESSION['ftp_user_pass'];

            $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
            $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
//            ftp_chdir($conn_id,$ftp_dir);

            $file = $_FILES['uploadfile']['tmp_name'];
            $remote_file =$ftp_dir.'/'. $_FILES['uploadfile']['name'];
            //    file_put_contents('file.txt','$file='.$file."\r\n",FILE_APPEND);
            //    file_put_contents('file.txt','$remote_file='.$remote_file."\r\n",FILE_APPEND);
            //   $file = fopen("ftp://travelink:travelink@example.com/test.txt","w");
            //    print_r(ftp_nlist($conn_id,"movie"));

            if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
                $this->addStaffLog('上传文件','上传文件：'.$_FILES['uploadfile']['name'].'  成功','upload');
                $this->error("文件:".$_FILES['uploadfile']['name']."上传成功");

            } else {
                $this->addStaffLog('上传文件','上传文件：'.$_FILES['uploadfile']['name'].'  失败','upload');
                $this->error( "上传失败");
            }
            ftp_close($conn_id);
        }
        $this->redirect(__APP__."/admin/ccgl");
    }
//public function test(){
//    $ftp_server='192.168.1.13';
//    $ftp_user_name='travelink';
//    $ftp_user_pass='travelink';
//    $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
//    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
//    print_r (ftp_raw($conn_id,"list"));
//}

    //单片价格管理
    public function singlepay(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $mname = $_GET['mname'];
        $hname = $_GET['hname'];
        $con=" where state !=9 ";
        if($hname){
            $con =$con." and  hotelname like '%".$hname."%' ";
        }
        if($mname){
            $con =$con." and  moviename like '%".$mname."%' ";
        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        //  $sql="select d.*,m.movie_addr,m.movie_pic,h.ipaddr from h_distribute d left join h_hotels h on d.hotelid=h.id left join h_movies m on d.movieid=m.id ";
        $sql = "select count(*) as zs from p_singletask ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select * from p_singletask  ".$con."  order by id desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("contentArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }

        }

        $this->hotelSelect();
        $this->movieSelect();

        unset($row_movie_sql);
        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['singlepay']);
        $this->display("admin/singlepay");
    }
    public function singlepayEdit()
    {
        $id=$_POST['id'];

        $hotelname = $_POST['hotelname'];
        $price=$_POST['movieprice'];
        if(!$hotelname){
            $this->error("酒店不能为空，请选择");
        }
        $moviename=$_POST['moviename'];
        if(!$moviename){
            $this->error("电影不能为空，请选择");
        }
        if($id){
            $sqls="SELECT * FROM `p_singletask` WHERE id=".$id;
            $rows = $this->model->query($sqls);
            if($rows){
                $price_pre=$rows[0]['price'];
            }
            $sql="UPDATE `p_singletask` SET `price`='{$price}' WHERE id=".$id;
            $row = $this->model->query($sql);
            if($price_pre!=$price){

                $content='任务id'.$id.'-酒店:'.$hotelname.'-电影:'.$moviename.'-价格 '.$price_pre.'改为 '.$price;
            }else{
                $content='任务id'.$id.'-酒店:'.$hotelname.'-电影:'.$moviename;
            }
            $this->addStaffLog('修改单片分发任务','修改单片分发任务：'.$content,'singlepay');
        }else{
            $hotelid =  substr($hotelname, 0, -1);
            $hotelidArr=explode(',',$hotelid);
            $content='';
            foreach ($hotelidArr as $hidval){
                $harr=explode('/',$hidval);
                $hid=$harr[0];
                $hotel=$harr[1];
                $sql="INSERT INTO `p_singletask`( `hotelid`, `hotelname`, `moviename`, `price`)VALUES ('{$hid}','{$hotel}','{$moviename}','{$price}')";
                $row = $this->model->query($sql);
                $id=mysql_insert_id();
                $content=$content.'任务id'.$id.'-酒店:'.$hotel.'-电影:'.$moviename.'-价格：'.$price.'；';
            }
            $this->addStaffLog('添加单片分发任务','添加单片分发任务：'.$content,'singlepay');
        }
        unset($row);
        unset($rows);
        $this->redirect(__APP__."/admin/singlepay");
    }
    public function startSinglepayTask(){
        $json ='{';
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        foreach ($strArr as $val){
            $sql = "UPDATE `p_singletask` SET `state`=1 WHERE id=".$val;
            $this->model->query($sql);
        }
        $this->addStaffLog('更新单片分发任务','开始单片分发任务id：'.$ids,'singlepay');
        $json .='"msg":"1"}';
        echo $json;
        exit;
    }
    //分发任务删除
    public function delallsinglepay(){
        $json ='{';
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $content='';
        foreach ($strArr as $val){
            $sqls="SELECT * FROM `p_singletask` WHERE id=".$val;
            $rows = $this->model->query($sqls);
            $hotel=$rows[0]['hotelname'];
            $movie=$rows[0]['moviename'];
            $content=$content.'任务id'.$val.'-酒店:'.$hotel.'-电影:'.$movie.'；';
            //  $sql = "delete from h_distribute where id=".$val;
            //删除任务需要下发，隐藏
            $sql = "UPDATE `p_singletask` SET `state`=9 WHERE id=".$val;
            $row = $this->model->query($sql);
        }
        $this->addStaffLog('删除单片分发任务','删除单片分发任务：'.$content,'singlepay');
        $json .='"msg":"1"}';
        unset($row);
        unset($rows);
        echo $json;
        exit;
    }
    //酒店选择
    public function hotelSelect(){
        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $this->assign("adminGroup",$adminGroup);
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $cong='';
        }

        $sql="SELECT id FROM `h_hotels_attribute` WHERE `attributeFlag`='movieUpload'";
        $rowAi = $this->model->query($sql);
        if($rowAi){
            $aid=$rowAi[0]['id'];
            $conAi=' and ai.attributeId='.$aid.' and ai.content=1';
            $conAiSql= ' left join h_hotelsid_attributeid ai on h.id=ai.hotelId';
        }else{
            $conAi='';
            $conAiSql='';
        }
        $sql="SELECT h.* FROM `h_hotels` h ".$consql_g.$conAiSql."  WHERE h.id>0 ".$cong.$conAi;
        $row = $this->model->query($sql);

        if($row){
            $row_json=json_encode($row);
            $this->assign("hotelsArr",$row_json);
        }
        $sql="SELECT groupname,id FROM `h_hotels_group` WHERE 1";
        $rowGroup = $this->model->query($sql);

        if($rowGroup){
            $row_json=json_encode($rowGroup);
            $this->assign("hotelsGroupArr",$rowGroup);
        }
    }
    //包名选择
    public function paynameSelect(){
        $sql="SELECT * FROM `p_allpayname` WHERE 1";
        $row = $this->model->query($sql);

        if($row){
            $row_json=json_encode($row);
            $this->assign("paynamesArr",$row_json);
        }

    }
    //电影选择
    public function movieSelect(){
        $sql="SELECT id,movie_name,movie_content FROM `h_movies` where 1 order by movie_stime,morder desc ";
        $row_movie_sql = $this->model->query($sql);
        $lists = array();
        if($row_movie_sql){
            foreach($row_movie_sql as $var){
                $movie_content=$var['movie_content'];
                $movie_content_arry=explode("#",$movie_content);
                $price=$movie_content_arry[1];
                $list = array(
                    'id'   =>  $var['id'],
                    'movie_name' => $var['movie_name'],
                    'price' =>  $price
                );
                array_push($lists,$list);
            }
            $row_json=json_encode($lists);
            $this->assign("moviesArr",$row_json);
        }
    }

    //按分组选择酒店
    public function hotelGroupSelected(){
        $hotelGroupId = $_POST['arr'];
        $row = $this->model->query("SELECT * FROM `h_hotels` WHERE groupId=".$hotelGroupId);
        if($row){
            $info='';
            foreach ($row as $val){
                $info=$info.$val['id'].'/'.$val['hotel'].',';
            }
            $json ='{"msg":"1","info":"'.$info.'"}';
        }else{
            $json ='{"msg":"0"}';
        }
        unset($row);
        echo $json;
        exit;
    }

    //全包价格管理
    public function allpay(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $mname = $_GET['mname'];
        $hname = $_GET['hname'];
        $con=" where state !=9 ";
        if($hname){
            $con =$con." and  hotelname like '%".$hname."%' ";
        }
        if($mname){
            $con =$con." and  payname like '%".$mname."%' ";
        }
        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $sql = "select count(*) as zs from p_allpaytask ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select * from p_allpaytask  ".$con."  order by id desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("contentArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }
        }

        $this->hotelSelect();
        //包名选择
        $this->paynameSelect();
        unset($row_movie_sql);
        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['allpay']);
        $this->display("admin/allpay");
    }

    //包片付费修改
    public function allpayEdit()
    {
        $id=$_POST['id'];

        $hotelname = $_POST['hotelname'];
        $price=$_POST['movieprice'];
        if(!$hotelname){
            $this->error("酒店不能为空，请选择");
        }
        $moviename=$_POST['payname'];
        if(!$moviename){
            $this->error("包名不能为空，请选择");
        }

        if($id){
            $sqls="SELECT * FROM `p_allpaytask` WHERE id=".$id;
            $rows = $this->model->query($sqls);
            if($rows){
                $price_pre=$rows[0]['price'];
            }
            $sql="UPDATE `p_allpaytask` SET `payname`='{$moviename}',`price`='{$price}' WHERE id=".$id;
            $row = $this->model->query($sql);
            if($price_pre!=$price){
                $content='任务id'.$id.'-酒店:'.$hotelname.'-包名:'.$moviename.'-价格 '.$price_pre.'改为 '.$price;
            }else{
                $content='任务id'.$id.'-酒店:'.$hotelname.'-包名:'.$moviename;
            }
            $this->addStaffLog('修改包片分发任务','修改包片分发任务：'.$content,'allpay');
        }else{
            $hotelid =  substr($hotelname, 0, -1);
            $hotelidArr=explode(',',$hotelid);
            $content='';
            foreach ($hotelidArr as $hidval){
                $harr=explode('/',$hidval);
                $hid=$harr[0];
                $hotel=$harr[1];
                $sql="INSERT INTO `p_allpaytask`(`hotelid`, `hotelname`, `payname`,  `price`)VALUES ('{$hid}','{$hotel}','{$moviename}','{$price}')";
                $row = $this->model->query($sql);
                $id=mysql_insert_id();
                $content=$content.'任务id'.$id.'-酒店:'.$hotel.'-包片:'.$moviename.'-价格：'.$price.'；';
            }
            $this->addStaffLog('添加包片分发任务','添加包片分发任务：'.$content,'allpay');
        }
        unset($row);
        unset($rows);
        $this->redirect(__APP__."/admin/allpay");
    }

    //删除包片任务
    public function delallpay(){
        $json ='{';
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $content='';
        foreach ($strArr as $val){
            $sqls="SELECT * FROM `p_allpaytask` WHERE id=".$val;
            $rows = $this->model->query($sqls);
            $hotel=$rows[0]['hotelname'];
            $movie=$rows[0]['payname'];
            $content=$content.'任务id'.$val.'-酒店:'.$hotel.'-包片:'.$movie.'；';
            //  $sql = "delete from h_distribute where id=".$val;
            //删除任务需要下发，隐藏
            $sql = "UPDATE `p_allpaytask` SET `state`=9 WHERE id=".$val;
            $row = $this->model->query($sql);
        }
        $this->addStaffLog('删除包片分发任务','删除包片分发任务：'.$content,'allpay');
        $json .='"msg":"1"}';
        unset($row);
        unset($rows);
        echo $json;
        exit;
    }
    //开始分发包片任务
    public function startAllpayTask(){
        $json ='{';
        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        foreach ($strArr as $val){
            $sql = "UPDATE `p_allpaytask` SET `state`=1 WHERE id=".$val;
            $this->model->query($sql);
        }
        $this->addStaffLog('更新包片分发任务','开始包片分发任务id：'.$ids,'allpay');
        $json .='"msg":"1"}';
        echo $json;
        exit;
    }

    //包名管理
    public function allpayName(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $hname = $_GET['name'];
        $con=" where id>0";
        if($hname){
            $con =$con." and  pname like '%".$hname."%' ";
        }

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $sql = "select count(*) as zs from p_allpayname ".$con;
        $row = $this->model->query($sql);
        if ($row){
            $count = $row[0][zs];
        }
        $sql = "select * from p_allpayname  ".$con."  order by id desc ".$limitStr;
        $list  =   $this->model->query($sql);
        if ($list){
            $this->assign('count',$count);
            $this->assign("contentArr",$list);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }
        }
        $sql="SELECT * FROM `p_allpayname` WHERE 1";
        $rowname = $this->model->query($sql);
        if($rowname){
            $this->assign("paynameArr",$rowname);
        }
        unset($rowname);
        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['allpayName']);
        $this->display("admin/allpayName");
    }

    //添加付费包
    public function addpayName(){
        $name = $_POST['name'];
        $period = $_POST['period'];
        $content = $_POST['content'];
        $id = $_POST['id'];
        if(!$name){
            $this->error('包名不能为空！');
        }
        if(!$period){
            $this->error('时间间隔不能为空！');
        }

        $row = $this->model->query("select * from p_allpayname where id ='".$id."'");
        if($row){
            $rowname = $this->model->query("select * from p_allpayname where pname ='".$name."'and id!='".$id."'");
            if($rowname){
                $this->error($name.'包名已存在！');
            }
            $this->model->query("UPDATE `p_allpayname` SET `pname`='{$name}',`period`='{$period}',`content`='{$content}' WHERE id='{$id}'");
            $this->addStaffLog('修改包名信息','修改包名信息：'.$name.'_时长：'.$period,'payName');
        }else {
            $rowname = $this->model->query("select * from p_allpayname where pname ='".$name."'");
            if($rowname){
                $this->error($name.'包名已存在！');
            }
            $this->model->query("insert into `p_allpayname`( `pname`, `period`,`content`)  values ('{$name}','{$period}','{$content}')");
            $this->addStaffLog('新增包名信息','新增包名信息：'.$name.'_时长：'.$period,'payName');
        }
        unset($row);
        $this->redirect(__APP__."/admin/allpayName");
    }
    //付费包删除
    public function delallpayName(){
        $msg = 1;

        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $username='';
        foreach ($strArr as $val){
            $sql = "select * from p_allpayname where  id=".$val;
            $row = $this->model->query($sql);
            if ($row){
                $username=$username.$row[0]['pname'].'、';
                $sql = "delete from p_allpayname where id=".$val ;
                $row = $this->model->query($sql);
            }else{
                $msg = 2;
            }
        }
        $this->addStaffLog('删除包名','删除包名：'.$username,'payName');
        $json ='{"msg":"'.$row.'"}';
        unset($row);
        echo $json;
        exit;
    }



    //酒店分组管理
    public function hotelGroup(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $name = $_GET['groupname'];
        if($name){
            $condition = "groupname like '%".$name."%'";
            $con=" where groupname like '%".$name."%' ";
        }

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=10;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);
        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

//        $count=$this->model->table('h_hotels_group')->where($condition)->count();
//        $sql = "select * from h_hotels_group ".$con.$limitStr;
//
//        $list  =   $this->model->query($sql);
//        $this->assign('count',$count);
//        if($listRows>=$count){
//            $this->assign('page','');
//        }else{
//            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
//        }
//        if(count($list)){
//            $this->assign("roomArr",$list);
//        }

        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['hotelGroup']);
        $this->display("admin/hotelGroup");
    }
    //酒店分组删除
    public function delallhotelGroup(){
        $msg = 1;

        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $username='';
        foreach ($strArr as $val){
            $sql = "select * from h_hotels_group where  id=".$val;
            $row = $this->model->query($sql);
            if ($row){
                $username=$username.$row[0]['groupname'].'、';
                $sql = "delete from h_hotels_group where id=".$val ;
                $row = $this->model->query($sql);
            }else{
                $msg = 2;
            }
        }
        $this->addStaffLog('删除酒店分类','删除酒店分类：'.$username,'hotelgroup');
        $json ='{"msg":"'.$row.'"}';
        unset($row);
        echo $json;
        exit;
    }

    //添加酒店分组
    public function addhotelGroup(){
        $groupname = $_POST['groupname'];

        $name =  $_POST['name'];
        $phone =  $_POST['phone'];
        $landline =  $_POST['landline'];
        $email =  $_POST['email'];
        $other =  $_POST['other'];
        $demand=$name.'@'.$phone.'@'.$landline.'@'.$email.'@'.$other;
        $time=time();
        $id = $_POST['id'];
        if(!$groupname){
            $this->error('酒店分类名不能为空！');
        }
        $row = $this->model->query("select * from h_hotels_group where id ='".$id."'");
        if($row){
            $row = $this->model->query("UPDATE `h_hotels_group` SET `groupname`='{$groupname}',`etime`='{$time}', `content`='{$demand}' WHERE id='{$id}'");
            $this->addStaffLog('修改酒店分类','修改酒店分类：'.$groupname,'hotelgroup');
        }else {

            $row = $this->model->query("insert into h_hotels_group ( `groupname`, `content`, `addtime`) values ('{$groupname}','{$demand}','{$time}')");
            $this->addStaffLog('新增酒店分类','新增酒店分类：'.$groupname,'hotelgroup');
        }
        if($row){
            unset($row);
            $this->error('更新成功！');
        }else{
            unset($row);
            $this->error('更新失败！');
        }
    }

    //开房统计
    public function  kftj(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
            $consql_griup=' left join h_hotels h on g.id=h.groupId';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $consql_griup='';
            $cong='';
        }
        $hotelname = $_GET['hotelname'];
        $stime = $_GET['stime']?$_GET['stime']:date('Y-m-01', strtotime(date("Y-m-d")));
        $etime = $_GET['etime']?$_GET['etime']:date('Y-m-d', strtotime("$stime +1 month -1 day"));
        $isExport = $_GET['isExport'];

        $con='';
        $conhotelid='';
        if($hotelname){
            $con =$con." and  d.hotelid =".$hotelname;
            $this->assign("hotelidSelect",$hotelname);
            $conhotelid=' and h.id='.$hotelname;
        }
        if($stime){
            $con =$con." and  d.stime >= '".$stime."' ";
        }
        if($etime){
            $con =$con." and  d.stime <= '".$etime."' ";
        }
        if($isExport){
            $headArry=array(
                'A'=> 'id',
                'B'=> '酒店名',
                'C'=> '时间',
                'D'=> '开机数',
                'E'=> '开机时长',
                'F'=> '设备类型',
                'G'=> '数据类型'
            );
            $rowExportData= $this->model->query("SELECT d.* FROM `h_hotels_data` d left join `h_hotels` h on d.hotelid=h.id ".$consql_g." WHERE d.id>0 ".$con.$cong .' order by d.hotelid,d.stime');
            if($rowExportData){
                $exportDataArry=array();
                $num=1;
                foreach($rowExportData as $ver){
                    $num++;
                    $exportData=array(
                        'A'.$num=> $ver['id'],
                        'B'.$num=> $ver['hotel'],
                        'C'.$num=> $ver['stime'],
                        'D'.$num=> $ver['clientNo'],
                        'E'.$num=> $ver['totalLength'],
                        'F'.$num=> $ver['deviceType'],
                        'G'.$num=> $ver['dataType']
                    );
                    array_push($exportDataArry,$exportData);
                }
                $this->exportData($headArry,$exportDataArry);
            }else{
               $this->error('没有满足条件的数据');
            }

        }

        $sqlc="SELECT count(*) as c,hotel FROM `h_hotels_data` d WHERE id>0 ".$con;
        $row= $this->model->query($sqlc);
        $count=$row[0]['c'];
        if($listRows>=$count){
            $this->assign('page','');
        }else{
            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
        }

        if($hotelname){
            $hotel_name=$row[0]['hotel'];
            $this->assign("hotel_name",$hotel_name);
        }

        $sql="SELECT h.*,g.groupname FROM `h_hotels` h left join h_hotels_group g on g.id=h.groupId ".$consql_g." where h.id>0 ".$cong." order by h.clientNo desc ";
        $list  =   $this->model->query($sql);
        if($list){
            $this->assign("hotelArr",$list);
        }

        $sqlCount="SELECT count(h.id) as hotelCount,sum(h.clientNo+h.clientNoPc+h.clientNoTv) as clientTotal,sum(h.clientNo) as clientXsNoTotal,sum(h.clientNoPc) as clientNoPcTotal,sum(h.clientNoTv) as clientNoTvTotal FROM `h_hotels` h ".$consql_g." WHERE h.id>0 ".$conhotelid.$cong;
        $listCount  =   $this->model->query($sqlCount);
        if($listCount){
            $this->assign("countArr",$listCount);
            $clientTotal=$listCount[0]['clientTotal'];
            $clientNoPcTotal=$listCount[0]['clientNoPcTotal'];
            $clientNoTvTotal=$listCount[0]['clientNoTvTotal'];
        }

        $tvflag = $_GET['tvflag'];
        $pcflag = $_GET['pcflag'];
        if($tvflag){
            $con=$con." and d.deviceType!='TV'" ;
            $clientTotal=$clientTotal-$clientNoTvTotal;
        }
        if($pcflag){
            $con=$con." and d.deviceType!='PC'" ;
            $clientTotal=$clientTotal-$clientNoPcTotal;
        }
        $this->assign("clientTotal",$clientTotal);
        $this->assign("tvflag",$tvflag);
        $this->assign("pcflag",$pcflag);
        $sqlTotal="SELECT sum(d.clientNo) as clientNo,DATE_FORMAT(d.stime,'%m-%d') as starttime FROM `h_hotels_data` d left join h_hotels h on d.hotelid=h.id ".$consql_g." WHERE d.dataLevel=1 ".$con.$cong." group by d.stime order by d.stime asc ";
        $rowTotal =   $this->model->query($sqlTotal);

        if($rowTotal){
            $categoriesTotal="[";
            $dataTotal="[";
//            $dataPerTotal="["; //单天 入住率
            $totaldateCount=0;
            $totalRoomCount=0;
            $totalRoomPerCount=0; //某时间段 入住率 之和
            foreach($rowTotal as $var){
                $categoriesTotal=$categoriesTotal."'".$var['starttime']."',";
                $dataTotal=$dataTotal.$var['clientNo'].",";
//                $dataPerTotal=$dataPerTotal.round(100*$var['clientNo']/$clientTotal,2).",";
                $totaldateCount=$totaldateCount+1;
                $totalRoomCount=$totalRoomCount+$var['clientNo'];
                $totalRoomPerCount=$totalRoomPerCount+round(100*$var['clientNo']/$clientTotal,2);
            }
            $pertotalRoomCount=round($totalRoomCount/$totaldateCount,2);
            $pertotalRoomPerCount=round($totalRoomPerCount/$totaldateCount,2);
            $this->assign("totalRoomCount",$totalRoomCount); //总入住数
            $this->assign("pertotalRoomCount",$pertotalRoomCount); //平均入住数
            $this->assign("pertotalRoomPerCount",$pertotalRoomPerCount); //平均入住率
            $datapertotalRoomCount="[";

            for($i=0;$i<$totaldateCount;$i++){
                $datapertotalRoomCount=$datapertotalRoomCount.$pertotalRoomCount.',';
            }
            $datapertotalRoomCount=substr($datapertotalRoomCount,0,-1);
            $datapertotalRoomCount=$datapertotalRoomCount."]";

            $categoriesTotal=substr($categoriesTotal,0,-1);
            $categoriesTotal=$categoriesTotal."]";
            $dataTotal=substr($dataTotal,0,-1);
            $dataTotal=$dataTotal."]";

        }
        if(!$categoriesTotal){
            $categoriesTotal=0;
        }
        if(!$dataTotal){
            $dataTotal=0;
        }
        $dataTotal=" [{
                        name: '入住数',
                        data: ".$dataTotal."
                    },{
                        name: '平均入住数',
                        data: ".$datapertotalRoomCount."
                    }]";

        $this->assign("categoriesTotal",$categoriesTotal);
        $this->assign("dataTotal",$dataTotal);


        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['kftj']);
        $this->display("admin/kftj");
    }

    public function checkOrder(){
        $cheskorder=$_POST['cheskorder']?$_POST['cheskorder']:'clientNo';
        $groupname=$_POST['groupname'];
        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $cong='';
        }

        if($groupname){
            $sql="SELECT h.*,g.groupname FROM `h_hotels` h left join h_hotels_group g on g.id=h.groupId ".$consql_g." where h.id>0 and g.groupname='{$groupname}'".$cong." order by h.".$cheskorder." desc ";
        }else{
            $sql="SELECT h.*,g.groupname FROM `h_hotels` h left join h_hotels_group g on g.id=h.groupId ".$consql_g." where h.id>0 ".$cong." order by h.".$cheskorder." desc ";
        }
        $list  =   $this->model->query($sql);
        $json_row=json_encode($list);
        $json ='{"msg":"1","row":'.$json_row.'}';
        echo $json;
        exit;
    }

    //集团统计
    public function  subsouGroup(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
            $consql_griup=' left join h_hotels h on g.id=h.groupId';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $consql_griup='';
            $cong='';
        }

        $sql="SELECT g.* FROM  h_hotels_group g ".$consql_griup.$consql_g." where g.id>0 ".$cong." group by g.id";
        $listGroup  =   $this->model->query($sql);
        if($listGroup){
            $this->assign("groupArr",$listGroup);
        }

        $groupname = $_GET['groupname'];
        $stime = $_GET['stime'];
        $etime = $_GET['etime'];
        $con='';

        if($stime){
            $con =$con." and  d.stime >= '".$stime."' ";
        }
        if($etime){
            $con =$con." and  d.stime <= '".$etime."' ";
        }


        $today=date('Y-m-d',time());
        $monthNow=date('m',time());
        if($groupname&&($groupname!='all')){
            $sqlCount="SELECT count(h.id) as hotelCount,sum(h.clientNo+h.clientNoPc+h.clientNoTv) as clientTotal,sum(h.clientNo) as clientXsNoTotal,sum(h.clientNoPc) as clientNoPcTotal,sum(h.clientNoTv) as clientNoTvTotal FROM `h_hotels` h ".$consql_g." WHERE h.groupId=".$groupname.$cong;
            $listCount  =   $this->model->query($sqlCount);
            if($listCount){
                $this->assign("countArr",$listCount);
            }
            $listName  =   $this->model->query("SELECT groupname FROM `h_hotels_group` WHERE id=".$groupname);
            if($listName){
                $groupNamestr=$listName[0]['groupname'];
                $this->assign("titleNamestr",$groupNamestr);
            }
            $con =$con." and  h.groupId =".$groupname;
            $sqlTotal="SELECT DATE_FORMAT(d.stime,'%Y-%m') as starttime FROM `h_hotels_data` d left join h_hotels h  on d.hotelid=h.id ".$consql_g." WHERE d.dataLevel=1 ".$con.$cong." group by starttime order by starttime desc limit 12";
            $rowTotal =   $this->model->query($sqlTotal);
            if($rowTotal){
//                $a=array_slice($rowTotal,0,12);
                $rowTotal=array_reverse($rowTotal);

                $categoriesTotal="[";
                $dataTV="{name: 'TV',data: [";
                $dataPC="{name: 'PC',data: [";
                $dataXS="{name: 'XS',data: [";
                $dataTVper="{name: 'TV',data: [";
                $dataPCper="{name: 'PC',data: [";
                $dataXSper="{name: 'XS',data: [";
                foreach($rowTotal as $var){
                    $TV=0;
                    $PC=0;
                    $XS=0;
                    $TVper=0;
                    $PCper=0;
                    $XSper=0;
                    $noTV=0;
                    $noPC=0;
                    $noXS=0;
                    $stime=$var['starttime'];

                    $sqlMonth= "SELECT sum(d.clientNo) as clientNo,d.deviceType,sum(d.`occupancyRate`)/count(d.`id`) as hotelMonthper FROM `h_hotels_data` d left join h_hotels h  on d.hotelid=h.id ".$consql_g." WHERE d.dataLevel=1 and d.operationStatus!='test' and DATE_FORMAT(d.stime,'%Y-%m')='{$stime}' ".$con.$cong." group by d.`hotelid`,d.deviceType ";

                    $rowMonth=   $this->model->query($sqlMonth);
                    if($rowMonth){
                        foreach($rowMonth as $v){
                            $clientNo=$v['clientNo'];
                            $deviceType=$v['deviceType'];
                            $hotelMonthper=$v['hotelMonthper'];
                            switch($deviceType){
                                case 'TV':$TV=$TV+$clientNo;
                                    $TVper=$TVper+$hotelMonthper;
                                    $noTV++;
                                    break;
                                case 'PC':$PC=$PC+$clientNo;
                                    $PCper=$PCper+$hotelMonthper;
                                    $noPC++;
                                    break;
                                case 'XS':$XS=$XS+$clientNo;
                                    $XSper=$XSper+$hotelMonthper;
                                    $noXS++;
                                    break;
                            }
                        }
                        if($noTV){
                            $TVper=round($TVper/$noTV,2);
                        }
                        if($noPC){
                            $PCper=round($PCper/$noPC,2);
                        }
                        if($noXS){
                            $XSper=round($XSper/$noXS,2);
                        }
                    }
                    $dataTV=$dataTV.$TV.",";
                    $dataPC=$dataPC.$PC.",";
                    $dataXS=$dataXS.$XS.",";

                    $dataTVper=$dataTVper.$TVper.",";
                    $dataPCper=$dataPCper.$PCper.",";
                    $dataXSper=$dataXSper.$XSper.",";

                    $categoriesTotal=$categoriesTotal."'".$var['starttime']."月',";
                }
            }

            $dataTV=substr($dataTV,0,-1);
            $dataTV=$dataTV."]}";
            $dataPC=substr($dataPC,0,-1);
            $dataPC=$dataPC."]}";
            $dataXS=substr($dataXS,0,-1);
            $dataXS=$dataXS."]}";

            $dataTVper=substr($dataTVper,0,-1);
            $dataTVper=$dataTVper."]}";
            $dataPCper=substr($dataPCper,0,-1);
            $dataPCper=$dataPCper."]}";
            $dataXSper=substr($dataXSper,0,-1);
            $dataXSper=$dataXSper."]}";

            $categoriesTotal=substr($categoriesTotal,0,-1);
            $categoriesTotal=$categoriesTotal."]";
            $dataTotal="[".$dataTV.",".$dataPC.",".$dataXS."]";
            $dataTotalper="[".$dataTVper.",".$dataPCper.",".$dataXSper."]";
        }else{
            $rowTotal=$listGroup;
            if($rowTotal){
                $categoriesTotal="[";
                $dataTV="{name: 'TV',data: [";
                $dataPC="{name: 'PC',data: [";
                $dataXS="{name: 'XS',data: [";
                $dataTVper="{name: 'TV',data: [";
                $dataPCper="{name: 'PC',data: [";
                $dataXSper="{name: 'XS',data: [";

                if(!$stime){
                    $stime=date('Y-m-d',time());
                }
                $this->assign("titleNamestr",date('Y-m月',strtotime($stime)));
                $stimeSql=date('Y-m',strtotime($stime));

                foreach($rowTotal as $var){
                    $TV=0;
                    $PC=0;
                    $XS=0;
                    $TVper=0;
                    $PCper=0;
                    $XSper=0;
                    $noTV=0;
                    $noPC=0;
                    $noXS=0;
                    $groupNamever=$var['groupname'];
                    $groupId=$var['id'];

                    $sqlMonth= "SELECT sum(d.clientNo) as clientNo,d.deviceType,sum(d.`occupancyRate`)/count(d.`id`) as hotelMonthper FROM `h_hotels_data` d left join h_hotels h  on d.hotelid=h.id ".$consql_g." WHERE d.dataLevel=1 and d.operationStatus!='test' and h.groupId='{$groupId}' and DATE_FORMAT(d.stime,'%Y-%m')='{$stimeSql}' ".$cong." group by d.`hotelid`,d.deviceType ";

                    $rowMonth=   $this->model->query($sqlMonth);
                    if($rowMonth){
                        foreach($rowMonth as $v){
                            $clientNo=$v['clientNo'];
                            $deviceType=$v['deviceType'];
                            $hotelMonthper=$v['hotelMonthper'];
                            switch($deviceType){
                                case 'TV':$TV=$TV+$clientNo;
                                    $TVper=$TVper+$hotelMonthper;
                                    $noTV++;
                                    break;
                                case 'PC':$PC=$PC+$clientNo;
                                    $PCper=$PCper+$hotelMonthper;
                                    $noPC++;
                                    break;
                                case 'XS':$XS=$XS+$clientNo;
                                    $XSper=$XSper+$hotelMonthper;
                                    $noXS++;
                                    break;
                            }
                        }
                        if($noTV){
                            $TVper=round($TVper/$noTV,2);
                        }
                        if($noPC){
                            $PCper=round($PCper/$noPC,2);
                        }
                        if($noXS){
                            $XSper=round($XSper/$noXS,2);
                        }
                    }

                    $dataTV=$dataTV.$TV.",";
                    $dataPC=$dataPC.$PC.",";
                    $dataXS=$dataXS.$XS.",";

                    $dataTVper=$dataTVper.$TVper.",";
                    $dataPCper=$dataPCper.$PCper.",";
                    $dataXSper=$dataXSper.$XSper.",";

                    $categoriesTotal=$categoriesTotal."'".$groupNamever."',";
                }

                $dataTV=substr($dataTV,0,-1);
                $dataTV=$dataTV."]}";
                $dataPC=substr($dataPC,0,-1);
                $dataPC=$dataPC."]}";
                $dataXS=substr($dataXS,0,-1);
                $dataXS=$dataXS."]}";

                $dataTVper=substr($dataTVper,0,-1);
                $dataTVper=$dataTVper."]}";
                $dataPCper=substr($dataPCper,0,-1);
                $dataPCper=$dataPCper."]}";
                $dataXSper=substr($dataXSper,0,-1);
                $dataXSper=$dataXSper."]}";

                $categoriesTotal=substr($categoriesTotal,0,-1);
                $categoriesTotal=$categoriesTotal."]";
                $dataTotal="[".$dataTV.",".$dataPC.",".$dataXS."]";
                $dataTotalper="[".$dataTVper.",".$dataPCper.",".$dataXSper."]";
            }
        }

        if(!$categoriesTotal){
            $categoriesTotal=0;
        }
        if(!$dataTotal){
            $dataTotal=0;
        }
        if(!$dataTotalper){
            $dataTotalper=0;
        }
        //echo $categoriesTotal;
        //        echo $dataTotal;
        //        exit;
        $this->assign("dataTotalper",$dataTotalper);
        $this->assign("categoriesTotal",$categoriesTotal);
        $this->assign("dataTotal",$dataTotal);

        //集团酒店数客房数 柱状图
        $sqlCount2="SELECT count(h.id) as hotelcount,sum(h.clientNo) as clientXsNoTotal,sum(h.clientNoPc) as clientNoPcTotal,sum(h.clientNoTv) as clientNoTvTotal,g.groupname FROM `h_hotels` h left join h_hotels_group g on h.groupId=g.id ".$consql_g." WHERE h.id>0 ".$cong." group by h.groupId";
        $rowCount2=   $this->model->query($sqlCount2);
        if($rowCount2){
            $categoriesTotal2="[";
            $dataTV2="{name: 'TV',data: [";
            $dataPC2="{name: 'PC',data: [";
            $dataXS2="{name: 'XS',data: [";
            $dataHotel2="{name: 'hotel',data: [";
            foreach($rowCount2 as $v2){
                $hotelcount=$v2['hotelcount'];
                $clientXsNoTotal=$v2['clientXsNoTotal'];
                $clientNoPcTotal=$v2['clientNoPcTotal'];
                $clientNoTvTotal=$v2['clientNoTvTotal'];
                $groupname=$v2['groupname'];

                $dataTV2=$dataTV2.$clientNoTvTotal.",";
                $dataPC2=$dataPC2.$clientNoPcTotal.",";
                $dataXS2=$dataXS2.$clientXsNoTotal.",";
                $dataHotel2=$dataHotel2.$hotelcount.',';

                $categoriesTotal2=$categoriesTotal2."'".$groupname."',";
            }
            $dataTV2=substr($dataTV2,0,-1);
            $dataTV2=$dataTV2."],stack: 'male'}";
            $dataPC2=substr($dataPC2,0,-1);
            $dataPC2=$dataPC2."],stack: 'male'}";
            $dataXS2=substr($dataXS2,0,-1);
            $dataXS2=$dataXS2."],stack: 'male'}";
            $dataHotel2=substr($dataHotel2,0,-1);
            $dataHotel2=$dataHotel2."],stack: 'female'}";

            $categoriesTotal2=substr($categoriesTotal2,0,-1);
            $categoriesTotal2=$categoriesTotal2."]";

            $dataRoomTotal="[".$dataTV2.",".$dataPC2.",".$dataXS2."]";
            $dataHotel2="[".$dataHotel2."]";

            $this->assign("dataRoomTotal",$dataRoomTotal);
            $this->assign("categoriesTotal2",$categoriesTotal2);
            $this->assign("dataHotel2",$dataHotel2);

        }

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['subsouGroup']);
        $this->display("admin/subsouGroup");
    }

    public function mViewStats(){
        $this->searchCondition();

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['mViewStats']);
        $this->display('admin/mViewStats');
    }
    public function doccin_mViewStats($datas, $consql, $con){
        $dataType=array(
            'xsMovie' => 'h_hotels_data_movieday',
            'Movie1905' => 'h_hotels_data_m1905day',
        );
        $hotelDatas=array();
        $moviedata=array();
        foreach($dataType as $keyType => $ver){
            //单片播放次数统计
            //单片播放时长统计
            $sql = 'select SUM(hd.count) as count,SUM(hd.duration) as duration ,hd.moviename from '.$ver.' hd '.$consql['movie'].'  where hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'"  '.$con['movie'].' group by hd.moviename ';
            $list = $this->model->query($sql);
            if($list){
                foreach($list as $k=>$v){
                    $moviedata[$keyType]['moviecount'][$k]=(int)$v['count'];
                    $moviedata[$keyType]['movieduration'][$k]=round($v['duration']/3600);
                    $moviedata[$keyType]['moviename'][$k]=$v['moviename'];
                }
                $moviedata[$keyType]['durationmoviename']=$moviedata[$keyType]['moviename'];

                $hotelDatas[$keyType]['countTotal']=array_sum($moviedata[$keyType]['moviecount']);
                $hotelDatas[$keyType]['durationTotal']=array_sum( $moviedata[$keyType]['movieduration']);

                array_multisort($moviedata[$keyType]['moviecount'], SORT_DESC,$moviedata[$keyType]['moviename']);
                array_multisort($moviedata[$keyType]['movieduration'], SORT_DESC,$moviedata[$keyType]['durationmoviename']);

                $hotelDatas[$keyType]['movieCount']=array(
                    'countArry' => array_slice($moviedata[$keyType]['moviecount'],0,10),
                    'movienameArry' => array_slice($moviedata[$keyType]['moviename'],0,10),
                    'titleNAme' => '单片电影播放次数top10'
                );
                $hotelDatas[$keyType]['movieDuration']=array(
                    'durationArry' => array_slice($moviedata[$keyType]['movieduration'],0,10),
                    'movienameArry' => array_slice($moviedata[$keyType]['durationmoviename'],0,10),
                    'titleNAme' => '单片电影播放时长top10'
                );
            }

            //酒店播放次数统计
            //酒店播放时长统计
            $sql = 'select SUM(hd.count) as count,SUM(hd.duration) as duration ,h.hotel from '.$ver.' hd '.$consql['movie'].'  where hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'"  '.$con['movie'].' group by hd.hotelid ';
            $list = $this->model->query($sql);
            if($list){
                foreach($list as $k=>$v){
                    $moviedata[$keyType]['hotelmoviecount'][$k]=(int)$v['count'];
                    $moviedata[$keyType]['hotelmovieduration'][$k]=round($v['duration']/3600);
                    $moviedata[$keyType]['hotelname'][$k]=$v['hotel'];
                }
                $moviedata[$keyType]['hotelDurationName']=$moviedata[$keyType]['hotelname'];

                array_multisort($moviedata[$keyType]['hotelmoviecount'], SORT_DESC,$moviedata[$keyType]['hotelname']);
                array_multisort($moviedata[$keyType]['hotelmovieduration'], SORT_DESC,$moviedata[$keyType]['hotelDurationName']);
                $hotelDatas[$keyType]['hotelMovieCount']=array(
                    'countArry' => array_slice($moviedata[$keyType]['hotelmoviecount'],0,10),
                    'hotelnameArry' => array_slice($moviedata[$keyType]['hotelname'],0,10),
                    'titleNAme' => '酒店播放电影次数top10'
                );
                $hotelDatas[$keyType]['hotelMovieDuration']=array(
                    'durationArry' => array_slice($moviedata[$keyType]['hotelmovieduration'],0,10),
                    'hotelnameArry' => array_slice($moviedata[$keyType]['hotelDurationName'],0,10),
                    'titleNAme' => '酒店播放电影时长top10'
                );
            }

            //按天统计点播次数
            $sql = 'select SUM(hd.count) as count,hd.stime from '.$ver.' hd '.$consql['movie'].'  where hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'"  '.$con['movie'].' group by hd.stime ';
            $list = $this->model->query($sql);
            if($list){
                foreach($list as $k=>$v){
                    $moviedata[$keyType]['movieStimecount'][$k]=(int)$v['count'];
                    $moviedata[$keyType]['moviestime'][$k]=$v['stime'];
                }
                array_multisort($moviedata[$keyType]['moviestime'], SORT_ASC,$moviedata[$keyType]['movieStimecount']);
                $hotelDatas[$keyType]['hotelMovieCountStime']=array(
                    'countStimeArry' => $moviedata[$keyType]['movieStimecount'],
                    'stimeArry' => $moviedata[$keyType]['moviestime'],
                    'titleNAme' => '酒店播放电影次数'
                );
            }
        }

        //小帅影院+m1905 => 酒店总观影次数
        $moviedata['hotelTotalCountArry'] = $moviedata['xsMovie']['hotelmoviecount'];
        if($moviedata['Movie1905']['hotelname']){
            foreach($moviedata['Movie1905']['hotelname'] as $k=>$v){
                $key=array_search($v,$moviedata['xsMovie']['hotelname'],true);
                if($key===0||$key){
                    $moviedata['hotelTotalCountArry'][$key]=(int)$moviedata['xsMovie']['hotelmoviecount'][$key]+(int)$moviedata['Movie1905']['hotelmoviecount'][$k];
                }
            }
        }

        array_multisort($moviedata['hotelTotalCountArry'], SORT_DESC,$moviedata['xsMovie']['hotelname']);
        $hotelDatas['hotelTotalCountArry']=array(
            'countArry' => array_slice($moviedata['hotelTotalCountArry'],0,10),
            'nameArry' => array_slice($moviedata['xsMovie']['hotelname'],0,10),
            'titleNAme' => '酒店播放电影总次数top10'
        );

        //开机总时长、总房间数、天数
        $sql = 'select SUM(hd.totalLength) as totalLength ,avg(hd.totalLength/hd.clientNo) as avgLength  from h_hotels_data hd '.$consql['g'].'  where hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'"  '.$con['g'];
//        echo $sql;

        $list = $this->model->query($sql);
        if($list){
            $totalLength=round($list[0]['totalLength']/3600,2);
            $avgLength=round($list[0]['avgLength']/3600,2);
        }
        //电视直播时长
        $sql = 'select SUM(hd.duration) as durationTV  from h_hotels_data_apk hd '.$consql['movie'].'  where hd.apkName like "%电视%" and  hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'"  '.$con['movie'];
        $list = $this->model->query($sql);
        if($list){
            $durationTV=round($list[0]['durationTV']/3600);
        }
//echo $sql;
        if($totalLength){
            $other=$totalLength-$durationTV-$hotelDatas['xsMovie']['durationTotal']-$hotelDatas['Movie1905']['durationTotal'];
            if($other<0){
                $other=0;
            }
            $hotelDatas['pie'][0]=array(
                0 => '小帅影院',
                1 => round(100*$hotelDatas['xsMovie']['durationTotal']/$totalLength,2)
            );
            $hotelDatas['pie'][1]=array(
                0 => 'm1905',
                1 => round(100*$hotelDatas['Movie1905']['durationTotal']/$totalLength,2)
            );
            $hotelDatas['pie'][2]=array(
                0 => '电视',
                1 => round(100*$durationTV/$totalLength,2)
            );
            $hotelDatas['pie'][3]=array(
                0 => '其他',
                1 => round(100*$other/$totalLength,2)
            );

            $hotelDatas['pieTable']=array(
                'avgLength' => $avgLength,
                'xs' => round($avgLength*$hotelDatas['pie'][0][1]/100,2),
                'm1905'  => round($avgLength*$hotelDatas['pie'][1][1]/100,2),
                'tv' => round($avgLength*$hotelDatas['pie'][2][1]/100,2),
                'other' => round($avgLength*$hotelDatas['pie'][3][1]/100,2)
            );
        }

//var_dump( $hotelDatas['pieTable']);
//        exit;
        return $hotelDatas;

    }
    //观影统计
    public function mViewStatsold(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on hh.id=a.hotelId ';
            $consql_Movie=' left join h_hotelsid_adminid a on dd.hotelid=a.hotelId ';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $consql_Movie='';
            $cong='';
        }

        $hotelname = $_GET['hotelname'];
        $stime = $_GET['stime'];
        $showDate = $_GET['showDate']; //显示周期
        $isExport = $_GET['isExport']; //是否导出


        $con='';
        if($hotelname){
            $hotelArry=explode('@',$hotelname);
            $hotelname=$hotelArry[1];
            $hotelid=$hotelArry[0];
            $this->assign("hotelname",$hotelname);
            $con =$con." and  dd.hotelid =".$hotelid;
        }
        if(!$stime){
            $stime=date("Y-m-d",strtotime("-1 day"));
        }

        //小帅电影观看次数柱状图
        $weekNo=0;
        if($showDate=='month'){
            $month=date('Y-m',strtotime($stime));
            $conMonth=$con." and  dd.monthNo = '".$month."' ";
            $rowMovie= $this->model->query("SELECT dd.* FROM `h_hotels_data_moviemonth` dd  ".$consql_Movie." WHERE dd.id>0 ".$conMonth.$cong." group by dd.moviename order by dd.count desc");
            if($rowMovie){
                $weekNo=$rowMovie[0]['monthNo'];
            }
            //小帅电影观看总次数、总时长
            $sqlViewMovie="SELECT sum(dd.count) as c,sum(dd.duration) as d FROM `h_hotels_data_moviemonth` dd  ".$consql_Movie." WHERE dd.id>0 ".$conMonth.$cong;

        }else{
            $conWeek =$con." and  dd.stime <= '".$stime."' and dd.etime>= '".$stime."'";
            $rowMovie= $this->model->query("SELECT dd.* FROM `h_hotels_data_movieweek` dd  ".$consql_Movie." WHERE dd.id>0 ".$conWeek.$cong." group by dd.moviename order by dd.count desc");
            $stimeWeek=0;
            $etimeWeek=0;
            if($rowMovie){
                $stimeWeek=$rowMovie[0]['stime'];
                $etimeWeek=$rowMovie[0]['etime'];
                $weekNo=$rowMovie[0]['weekNo'];
            }
            //小帅电影观看总次数、总时长
            $sqlViewMovie="SELECT sum(dd.count) as c,sum(dd.duration) as d FROM `h_hotels_data_movieweek` dd ".$consql_Movie." WHERE dd.id>0 ".$conWeek.$cong;
        }
        $categoriesTmax=0;
        $dataTmax=0;
        if($rowMovie){
            $movieArry=array_slice($rowMovie,0,10);
            $categoriesTmax="[";
            $dataTmax="[";
            foreach($movieArry as $var){
                $categoriesTmax=$categoriesTmax."'".$var['moviename']."',";
                $dataTmax=$dataTmax.$var['count'].",";
            }
            $categoriesTmax=substr($categoriesTmax,0,-1);
            $categoriesTmax=$categoriesTmax."]";
            $dataTmax=substr($dataTmax,0,-1);
            $dataTmax=$dataTmax."]";
            if(!$categoriesTmax){
                $categoriesTmax=0;
            }
            if(!$dataTmax){
                $dataTmax=0;
            }
        }
        $this->assign("categoriesTmax",$categoriesTmax);
        $this->assign("dataTmax",$dataTmax);

        //m1905电影观看次数柱状图
        if($showDate=='month'){
            $month=date('Y-m',strtotime($stime));
            $conMonth=$con." and  dd.monthNo = '".$month."' ";
            $rowMovieM1905= $this->model->query("SELECT dd.* FROM `h_hotels_data_m1905month` dd  ".$consql_Movie." WHERE dd.id>0 ".$conMonth.$cong." group by dd.moviename order by dd.count desc");
            if(!$weekNo){
                if($rowMovieM1905){
                    $weekNo=$rowMovieM1905[0]['monthNo'];
                }
            }
            //m1905电影观看总次数、总时长、内容
            $sqlViewMovieM1905="SELECT sum(dd.count) as c,sum(dd.duration) as d FROM `h_hotels_data_m1905month` dd  ".$consql_Movie." WHERE dd.id>0  ".$conMonth.$cong;
        }else{
            $conWeek =$con." and  dd.stime <= '".$stime."' and dd.etime>= '".$stime."'";
            $rowMovieM1905= $this->model->query("SELECT dd.* FROM `h_hotels_data_m1905week` dd ".$consql_Movie." WHERE dd.id>0 ".$conWeek.$cong." group by dd.moviename order by dd.count desc");
            if(!$weekNo){
                if($rowMovieM1905){
                    $stimeWeek=$rowMovieM1905[0]['stime'];
                    $etimeWeek=$rowMovieM1905[0]['etime'];
                    $weekNo=$rowMovieM1905[0]['weekNo'];
                }
            }
            //m1905电影观看总次数、总时长、内容
            $sqlViewMovieM1905="SELECT sum(dd.count) as c,sum(dd.duration) as d FROM `h_hotels_data_m1905week` dd  ".$consql_Movie." WHERE dd.id>0 ".$conWeek.$cong;
        }
        $categoriesTmaxM1905=0;
        $dataTmaxM1905=0;
        if($rowMovieM1905){
            $movieArryM1905=array_slice($rowMovieM1905,0,10);
            $categoriesTmaxM1905="[";
            $dataTmaxM1905="[";
            foreach($movieArryM1905 as $varM1905){
                $categoriesTmaxM1905=$categoriesTmaxM1905."'".$varM1905['moviename']."',";
                $dataTmaxM1905=$dataTmaxM1905.$varM1905['count'].",";
            }
            $categoriesTmaxM1905=substr($categoriesTmaxM1905,0,-1);
            $categoriesTmaxM1905=$categoriesTmaxM1905."]";
            $dataTmaxM1905=substr($dataTmaxM1905,0,-1);
            $dataTmaxM1905=$dataTmaxM1905."]";
            if(!$categoriesTmaxM1905){
                $categoriesTmaxM1905=0;
            }
            if(!$dataTmaxM1905){
                $dataTmaxM1905=0;
            }
        }
        $this->assign("categoriesTmaxM1905",$categoriesTmaxM1905);
        $this->assign("dataTmaxM1905",$dataTmaxM1905);

        if($showDate=='month'){
            $subtitle='统计时间段：'.$weekNo.'月 ';
            //开机总房间数、总时长条件
            $conTotalRoom=$con." and DATE_FORMAT(dd.stime,'%Y-%m')='".$month."'";

            //按月统计条件内每天总点击数
            $rowMovieCountArry= $this->model->query("SELECT sum(dd.count) as c,dd.stime FROM `h_hotels_data_movieday` dd  ".$consql_Movie." WHERE dd.id>0 and DATE_FORMAT( dd.stime,'%Y-%m') ='{$month}' ".$con.$cong."  group by dd.stime order by dd.stime asc");
            $rowMovie1905CountArry= $this->model->query("SELECT sum(dd.count) as c,dd.stime FROM `h_hotels_data_m1905day` dd  ".$consql_Movie." WHERE dd.id>0 and DATE_FORMAT( dd.stime,'%Y-%m') ='{$month}' ".$con.$cong."  group by dd.stime order by dd.stime asc");
        }else{
            $subtitle='统计时间段：'.$weekNo.'周 '.$stimeWeek.'至'.$etimeWeek;
            //开机总房间数、总时长条件
            $conTotalRoom=$con." and dd.stime>='".$stimeWeek."' and dd.stime <='".$etimeWeek."'";

            //按周统计条件内每天总点击数
            $rowMovieCountArry= $this->model->query("SELECT sum(dd.count) as c,dd.stime FROM `h_hotels_data_movieday` dd  ".$consql_Movie." WHERE dd.id>0 and dd.stime >='{$stimeWeek}' and dd.stime <='{$etimeWeek}' ".$con.$cong."  group by dd.stime order by dd.stime asc");
            $rowMovie1905CountArry= $this->model->query("SELECT sum(dd.count) as c,dd.stime FROM `h_hotels_data_m1905day` dd  ".$consql_Movie." WHERE dd.id>0 and dd.stime >='{$stimeWeek}' and dd.stime <='{$etimeWeek}' ".$con.$cong."  group by dd.stime order by dd.stime asc");
        }
        $this->assign("subtitle",$subtitle);

        //按各酒店平均每天每间时长 统计开机总时长
        $rowTotalCount= $this->model->query("SELECT sum(dd.clientNo) as c,sum(dd.totalLength) as d ,dd.hotelid ,count(distinct(dd.stime)) as dateNo FROM `h_hotels_data` dd  ".$consql_Movie." WHERE dd.id and dd.dataLevel=1 ".$conTotalRoom.$cong." group by dd.hotelid " );
        if($rowTotalCount){
            $no=0;
            $startLengthPer=0;//单酒店平均每天每间开机时长
            $startNoTotal=0;//开机总房间数
            $startTotalLength=0; //开机总时长
            $tvLengthPer=0;
            $viewLengthPer=0;
            $m1905LengthPer=0;

            foreach($rowTotalCount as $ver){
                $clientNo=$ver['c'];
                $startNoTotal=$startNoTotal+$clientNo;
                $startLength=$ver['d'];
                $startTotalLength=$startTotalLength+$startLength;
                $dateNo=$ver['dateNo'];
                $startLengthPer=$startLengthPer+$startLength/($clientNo);
                $hotelid=$ver['hotelid'];

                //电视
                $rowTotalTV= $this->model->query("SELECT sum(dd.duration) as d FROM `h_hotels_data_apk` dd  ".$consql_Movie." WHERE  dd.apkName='电视直播' and dd.duration>0 and dd.hotelid='{$hotelid}' ".$conTotalRoom);
                if($rowTotalTV){
                    $tvLength=$rowTotalTV[0]['d'];
                }
                $tvLengthPer=$tvLengthPer+$tvLength/($clientNo);

                //小帅电影观看时长
                $rowViewTotal= $this->model->query($sqlViewMovie." and dd.hotelid='{$hotelid}'");
                if($rowViewTotal){
                    $viewLength=$rowViewTotal[0]['d'];
                }
                $viewLengthPer=$viewLengthPer+$viewLength/($clientNo);

                //m1905电影观看时长
                $rowViewTotalM1905= $this->model->query($sqlViewMovieM1905." and dd.hotelid='{$hotelid}'");
                if($rowViewTotalM1905){
                    $m1905Length=$rowViewTotalM1905[0]['d'];
                }
                $m1905LengthPer=$m1905LengthPer+$m1905Length/($clientNo);
                $no=$no+1;
            }

            $startTotalLengthPer=$startLengthPer/$no;
            $tvTotalLengthPer=$tvLengthPer/$no;
            $viewTotalLengthPer=$viewLengthPer/$no;
            $m1905TotalLengthPer=$m1905LengthPer/$no;
            $otherTotalLengthPer=$startTotalLengthPer-$tvTotalLengthPer-$m1905TotalLengthPer-$viewTotalLengthPer;
            if($otherTotalLengthPer<0){
                $otherTotalLengthPer=0;
            }
        }else{
            $startNoTotal=1;
            $startTotalLengthPer=1;
            $tvTotalLengthPer=0;
            $viewTotalLengthPer=0;
            $m1905TotalLengthPer=0;
            $otherTotalLengthPer=0;
        }

        $this->assign("TotalRoom",$startNoTotal);

        $lengthTotalRoomPer=round($startTotalLengthPer/(60*60),3); //平均每间房每天
        $lengthTotalTVPer=round($tvTotalLengthPer/(60*60),3); //平均每间房每天
        $lengthTotalViewPer=round($viewTotalLengthPer/(60*60),3); //平均每间房每天
        $lengthTotalViewM1905Per=round($m1905TotalLengthPer/(60*60),3); //平均每间房每天
        $otherPer=round($otherTotalLengthPer/(60*60),3); //平均每间房每天

        $this->assign("lengthTotalTV",$lengthTotalTVPer);
        $this->assign("lengthTotalRoom",$lengthTotalRoomPer);
        $this->assign("lengthTotalView",$lengthTotalViewPer);
        $this->assign("lengthTotalViewM1905",$lengthTotalViewM1905Per);
        $this->assign("otherLth",$otherPer);

        //电影观看时长占比饼图
        $lengthTotalViewM1905Per=round(100*$m1905TotalLengthPer/$startTotalLengthPer,2);
        $lengthTotalViewPer=round(100*$viewTotalLengthPer/$startTotalLengthPer,2);
        $lengthTotalTVPer=round(100*$tvTotalLengthPer/$startTotalLengthPer,2);
        $other_length_per=round(100*$otherTotalLengthPer/$startTotalLengthPer,2);
        $strPie="{name:'电影',
                   y:$lengthTotalViewPer,
                   sliced: true,
                   selected: true},";
        $strPie=$strPie."['m1905',$lengthTotalViewM1905Per],";
        $strPie=$strPie."['电视',$lengthTotalTVPer],";
        $strPie=$strPie."['其他',$other_length_per]";
        $piedata="[$strPie]";
        $this->assign("piedata",$piedata);
        $this->assign("lengthTotalTVPer",$lengthTotalTVPer);
        $this->assign("lengthTotalViewPer",$lengthTotalViewPer);
        $this->assign("lengthTotalViewM1905Per",$lengthTotalViewM1905Per);
        $this->assign("otherLthPer",$other_length_per);

        //总点播次数趋势图
        $viewTotal=0; //小帅电影总点播次数
        $m1905Total=0; //m1905电影总点播次数
        if($rowMovie1905CountArry){
            $m1905Arry=array();
            foreach($rowMovie1905CountArry as $var){
                $stime=$var['stime'];
                $m1905Arry[$stime]=$var['c'];
                $m1905Total=$m1905Total+$var['c'];
            }
        }
        if($rowMovieCountArry){
            $categoriesTotal="[";
            $dataTotal="[";
            $data1905Total="[";
            foreach($rowMovieCountArry as $var){
                $stime=$var['stime'];
                $categoriesTotal=$categoriesTotal."'".$stime."',";
                $dataTotal=$dataTotal.$var['c'].",";
                $viewTotal=$viewTotal+$var['c'];
                $data1905Total=$data1905Total.$m1905Arry[$stime].",";
            }
            $categoriesTotal=substr($categoriesTotal,0,-1);
            $categoriesTotal=$categoriesTotal."]";
            $dataTotal=substr($dataTotal,0,-1);
            $dataTotal=$dataTotal."]";
            $data1905Total=substr($data1905Total,0,-1);
            $data1905Total=$data1905Total."]";
        }

        if(!$data1905Total){
            $data1905Total=0;
        }
        if(!$categoriesTotal){
            $categoriesTotal=0;
        }
        if(!$dataTotal){
            $dataTotal=0;
        }

        $countPer=round($viewTotal/$startNoTotal,2);
        $this->assign("countPer",$countPer);
        $countPerM1905=round($m1905Total/$startNoTotal,2);
        $this->assign("countPerM1905",$countPerM1905);
        $this->assign("viewTotal",$viewTotal);
        $this->assign("viewTotalM1905",$m1905Total);

        $this->assign("categoriesTotalCount",$categoriesTotal);
        $this->assign("dataTotalCount",$dataTotal);
        $this->assign("data1905TotalCount",$data1905Total);


        //所有酒店列表
        $sql="SELECT hh.* FROM `h_hotels` hh ".$consql_g." where hh.id>0".$cong;
        $list  =   $this->model->query($sql);
        if($list){
            $this->assign("hotelArr",$list);
        }


        //电影数据导出
        if($isExport){
            $headArry=array(
                'A'=> 'id',
                'B'=> '电影名',
                'C'=> '点播次数',
                'D'=> '播放时长',
                'E'=> '酒店名',
                'F'=> '时间',
                'G'=> '电影分类'
            );

            $rowExportData= $this->model->query("SELECT dd.*,h.hotel FROM `h_hotels_data_movieday` dd left join `h_hotels` h on dd.hotelid=h.id ".$consql_g." WHERE dd.id>0   ".$con.$conTotalRoom.$cong .' order by dd.hotelid,dd.stime');
            if($rowExportData){
                $exportDataArry=array();
                $num=1;
                foreach($rowExportData as $ver){
                    $num++;
                    $exportData=array(
                        'A'.$num=> $ver['id'],
                        'B'.$num=> $ver['moviename'],
                        'C'.$num=> $ver['count'],
                        'D'.$num=> $ver['duration'],
                        'E'.$num=> $ver['hotel'],
                        'F'.$num=> $ver['stime'],
                        'G'.$num=> $ver['moviemenu']
                    );
                    array_push($exportDataArry,$exportData);
                }
                $this->exportData($headArry,$exportDataArry);
            }else{
                $this->error('没有满足条件的数据');
            }

        }

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['mViewStats']);
        $this->display("admin/mViewStats");
    }

    /**
     * 根据第几周获取本周的开始时间与最后时间
     * @param int $year 年份 $weeks = get_week($year)
     * @param 如获取第18周的开始时间$weeks[18][0]
     * @param 如获取第18周的最后时间$weeks[18][1]
     */
    static  public function get_week($year) {
        $year_start = $year . "-01-01";
        $year_end = $year . "-12-31";
        $startday = strtotime($year_start);
        if (intval(date('N', $startday)) != '1') {
            $startday = strtotime("next monday", strtotime($year_start)); //获取年第一周的日期
        }
        $year_mondy = date("Y-m-d", $startday); //获取年第一周的日期

        $endday = strtotime($year_end);
        if (intval(date('W', $endday)) == '7') {
            $endday = strtotime("last sunday", strtotime($year_end));
        }

        $num = intval(date('W', $endday));
        for ($i = 1; $i <= $num; $i++) {
            $j = $i -1;
            $start_date = date("Y-m-d", strtotime("$year_mondy $j week "));

            $end_day = date("Y-m-d", strtotime("$start_date +6 day"));

            $week_array[$i] = array (
                str_replace("-",
                    "",
                    $start_date
                ), str_replace("-", "", $end_day));
        }
        return $week_array;
    }
    public function test(){
        $data=$_GET['data'];
        $arry=explode('-',$data);
        $year=$arry[0];
        $week=$arry[1];
        $weeks=$this->get_week($year);
        var_dump($weeks[$week]);
        exit;
    }

    //m1905电影数据导入
    public function m1905import(){
        $this->assign("canshu",'m1905import');
        require(CP_PATH.'ext/PHPExcel.php');
        if($_POST){
            $filename='public/temp/1.xls';
            $error = array('请选择上传数据包！','读取数据包失败！','请检查上传数据包,下列位置数据不能为空:',
                '插入顶级分类数据失败！','二级分类插入失败！','插入电影失败！',' 数据包格式有问题,请确认下上传XLS格式数据包！','电影路径有问题，请检查数据包格式！','内容不存在','名称不能有空格');

            if (!$_FILES[movefile][name]){
                $this->assign("error",$error[0]);
                $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['mViewStats']);
                $this->display("admin/import");
                exit;
//            }elseif($_FILES[movefile][type]!='application/vnd.ms-excel'){
//                $this->assign("error",$error[6]);
            }else {

                $xls_error  = '';
                move_uploaded_file($_FILES["movefile"]["tmp_name"], $filename);

                $PHPReader = new PHPExcel_Reader_Excel2007();
                if(!$PHPReader->canRead($filename)){
                    $PHPReader = new PHPExcel_Reader_Excel5();
                    if(!$PHPReader->canRead($filename)){
                        $this->assign("error",$error[1]);
                    }
                }

                $PHPExcel = $PHPReader->load($filename);
                $currentSheet = $PHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();
                $allRow = $currentSheet->getHighestRow();
                for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){
                    for($colIndex='A';$colIndex<='E';$colIndex++){
                        $addr = $colIndex.$rowIndex;
                        $cell = $currentSheet->getCell($addr)->getValue();
                        if($cell instanceof PHPExcel_RichText)
                            $cell = $cell->__toString();
                        if( $cell==""){
                            $xls_error = '1';
                            $error_desc .= $addr.',';
                        }
                    }
                }

                if($xls_error){
                    $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['mViewStats']);
                    $this->display("admin/import");
                    $this->assign("error",$error[2].$error_desc);
                }else{
                    $import_movie_name='';
                    $import_hotel_name='';
                    for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){
                        $movieName = $currentSheet->getCell('A'.$rowIndex)->getValue();
                        $hotelName  = $currentSheet->getCell('B'.$rowIndex)->getValue();
                        $stime  = $currentSheet->getCell('D'.$rowIndex)->getValue();
                        $length  = $currentSheet->getCell('E'.$rowIndex)->getValue();

                        if($movieName instanceof PHPExcel_RichText)
                            $movieName = $movieName->__toString();
                        if($hotelName instanceof PHPExcel_RichText)
                            $hotelName = $hotelName->__toString();
                        if($stime instanceof PHPExcel_RichText)
                            $stime = $stime->__toString();
                        if($length instanceof PHPExcel_RichText)
                            $length = $length->__toString();

                        $hour=strstr($length,'小时',true);
                        if($hour){
                            $length=str_replace('小时','',strstr($length,'小时'));
                        }
                        $m=strstr($length,'分',true);
                        if($m){
                            $length=str_replace('分','',strstr($length,'分'));
                        }
                        $s=strstr($length,'秒',true);
                        $duration=$hour*3600+$m*60+$s;
                        $stime=date('Y-m-d',strtotime($stime));
                        $row = $this->model->query("SELECT id FROM `h_hotels` WHERE hotel='{$hotelName}'");
                        if($row){
                            $hotelid=$row[0]['id'];
                            $movieRow=$this->model->query("SELECT `id`,duration FROM `h_hotels_data_m1905day` WHERE hotelid='{$hotelid}' and moviename='{$movieName}' and stime='{$stime}'");
                            if($movieRow){
                                $id=$movieRow[0]['id'];
                                $duration=$movieRow[0]['duration']+$duration;
                                $this->model->query("UPDATE `h_hotels_data_m1905day` SET `count`=count+1,`duration`='{$duration}' WHERE id=".$id);
                            }else{
                                $this->model->query("INSERT INTO `h_hotels_data_m1905day`( `hotelid`, `rstate`, `count`, `duration`, `moviename`, `stime`) VALUES ('{$hotelid}',0,1,'{$duration}','{$movieName}','{$stime}')");
                            }
                            $import_movie_name.=$movieName.',';
                        }else {
                            $import_hotel_name .= $hotelName.',';
                        }
                    }
                    $this->m1905moviedataWeek();
                    $this->m1905moviedataMonth();

                    $this->assign("success",'数据处理成功！<br/>新增内容:'.$import_movie_name.",<br/>");
                    if($import_hotel_name){
                        $this->assign("success",'酒店名不存在！<br/>名称:'.$import_hotel_name.",<br/>");
                    }
                    $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['mViewStats']);
                    $this->display("admin/import");
                    exit;
                }
            }
        }
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['mViewStats']);
        $this->display("admin/import");
    }
    //m1905电影 按周存储数据
    public function m1905moviedataWeek(){
        $row=$this->model->query("SELECT  `hotelid` , SUM(  `count` ) AS c, SUM(  `duration` ) AS d,  `moviename` ,  `moviemenu` , DATE_FORMAT(stime,  '%X-%V' ) AS yearWeek, stime , SUBDATE( stime, DATE_FORMAT( stime,  '%w' ) ) AS startWeek ,
        SUBDATE( stime, DATE_FORMAT(stime,  '%w' ) -6 ) AS endWeek FROM  `h_hotels_data_m1905day` WHERE rstate =0 GROUP BY hotelid, yearWeek , moviename  ");
        if($row){
            foreach($row as $var){
                $hotelid=$var['hotelid'];
                $count=$var['c'];
                $duration=$var['d'];
                $moviename=$var['moviename'];
                $moviemenu=$var['moviemenu'];
                $yearWeek=$var['yearWeek'];
                $startWeek=$var['startWeek'];
                $endWeek=$var['endWeek'];
                $rowsWeek=$this->model->query("SELECT `id`,`count`,`duration`  FROM `h_hotels_data_m1905week` WHERE `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and `weekNo`='{$yearWeek}'");
                if($rowsWeek){
                    $weedid=$rowsWeek[0]['id'];
                    $durationNew=$rowsWeek[0]['duration']+$duration;
                    $countNew=$rowsWeek[0]['count']+$count;
                    $r=$this->model->query("UPDATE `h_hotels_data_m1905week` SET `count`='{$countNew}',`duration`='{$durationNew}' WHERE id=".$weedid);
                }else{
                    $r=$this->model->query("INSERT INTO `h_hotels_data_m1905week`( `hotelid`, `count`, `duration`, `moviename`, `moviemenu`,  `stime`, `etime`, `weekNo`) VALUES ('{$hotelid}','{$count}','{$duration}','{$moviename}','{$moviemenu}','{$startWeek}','{$endWeek}','{$yearWeek}')");
                }
                if($r){
                    $this->model->query("UPDATE `h_hotels_data_m1905day` SET `rstate`=1 WHERE rstate=0 and `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and DATE_FORMAT( stime,  '%X-%V' )='{$yearWeek}'");
                }
            }
        }

    }

    //m1905电影 按月存储数据
    public function m1905moviedataMonth(){
        $row=$this->model->query("SELECT  `hotelid` , SUM(  `count` ) AS c, SUM(  `duration` ) AS d,  `moviename` ,  `moviemenu` , DATE_FORMAT( stime,  '%Y-%m' ) AS yearMonth  FROM  `h_hotels_data_m1905day` WHERE rstate =1 GROUP BY hotelid,yearMonth , moviename ");
        if($row){
            foreach($row as $var){
                $hotelid=$var['hotelid'];
                $count=$var['c'];
                $duration=$var['d'];
                $moviename=$var['moviename'];
                $moviemenu=$var['moviemenu'];
                $yearMonth=$var['yearMonth'];
                $rowsWeek=$this->model->query("SELECT `id`,`count`,`duration`  FROM `h_hotels_data_m1905month` WHERE `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and `monthNo`='{$yearMonth}'");

                if($rowsWeek){
                    $weedid=$rowsWeek[0]['id'];
                    $durationNew=$rowsWeek[0]['duration']+$duration;
                    $countNew=$rowsWeek[0]['count']+$count;
                    $r=$this->model->query("UPDATE `h_hotels_data_m1905month` SET `count`='{$countNew}',`duration`='{$durationNew}' WHERE id=".$weedid);
                }else{
                    $r=$this->model->query("INSERT INTO `h_hotels_data_m1905month`( `hotelid`, `count`, `duration`, `moviename`, `moviemenu`,   `monthNo`) VALUES ('{$hotelid}','{$count}','{$duration}','{$moviename}','{$moviemenu}','{$yearMonth}')");
                }
                if($r){
                    $this->model->query("UPDATE `h_hotels_data_m1905day` SET `rstate`=2 WHERE rstate=1 and `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and DATE_FORMAT( stime,'%Y-%m')='{$yearMonth}'");
                }
            }
        }

    }

    //酒店区域管理
    public function hotelArea(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $name = $_GET['groupname'];
        if($name){
            $condition = "areaname like '%".$name."%'";
            $con=" where areaname like '%".$name."%' ";
        }

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=10;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);
        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

        $count=$this->model->table('h_hotels_area')->where($condition)->count();
        $sql = "select * from h_hotels_area ".$con.$limitStr;

        $list  =   $this->model->query($sql);
        $this->assign('count',$count);
        if($listRows>=$count){
            $this->assign('page','');
        }else{
            $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
        }
        if(count($list)){
            $this->assign("roomArr",$list);
        }
        $this->hotelSelect();
        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['hotelArea']);
        $this->display("admin/hotelArea");
    }
    //酒店区域删除
    public function delallhotelArea(){
        $msg = 1;

        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $username='';
        foreach ($strArr as $val){
            $sql = "select * from h_hotels_area where  id=".$val;
            $row = $this->model->query($sql);
            if ($row){
                $username=$username.$row[0]['areaname'].'、';
                $sql = "delete from h_hotels_area where id=".$val ;
                $row = $this->model->query($sql);
                $this->model->query("DELETE FROM `h_hotelsid_areaid` WHERE areaId=".$val);
            }else{
                $msg = 2;
            }
        }
        $this->addStaffLog('删除酒店区域','删除酒店区域：'.$username,'hotelarea');
        $json ='{"msg":"'.$row.'"}';
        unset($row);
        echo $json;
        exit;
    }

    //添加酒店分组
    public function addhotelArea(){
        $groupname = $_POST['areaname'];


        $time=time();
        $id = $_POST['id'];
        if(!$groupname){
            $this->error('酒店区域名不能为空！');
        }
        $row = $this->model->query("select * from h_hotels_area where id ='".$id."'");
        if($row){
            $row = $this->model->query("UPDATE `h_hotels_area` SET `areaname`='{$groupname}',`etime`='{$time}' WHERE id='{$id}'");
            $this->addStaffLog('修改酒店区域','修改酒店区域：'.$groupname,'hotelarea');
        }else {

            $row = $this->model->query("insert into h_hotels_area ( `areaname`,`addtime`) values ('{$groupname}','{$time}')");
            $this->addStaffLog('新增酒店区域','新增酒店区域：'.$groupname,'hotelarea');
        }
        if($row){
            unset($row);
            $this->error('更新成功！');
        }else{
            unset($row);
            $this->error('更新失败！');
        }
    }

    //酒店区域选择
    public function selecthotelArea(){
        $ids = $_POST['id'];
        $row=$this->model->query("SELECT hh.hotel FROM `h_hotelsid_areaid` ii left join h_hotels hh on ii.`hotelId`=hh.id WHERE ii.`areaId`=".$ids);
        $str='';
        if($row){
            foreach($row as $v){
                $str=$str.$v['hotel'].',';
            }
        }
        $json ='{"msg":"'.$str.'"}';
        unset($row);
        echo $json;
        exit;
    }

    //关联酒店、区域
    public function join_hotel_Area(){
        $hotelname = $_POST['hotelname'];

        $time=time();
        $id = $_POST['areaid'];
        if(!$hotelname){
            $this->error('酒店名不能为空！');
        }

        $this->model->query("DELETE FROM `h_hotelsid_areaid` WHERE `areaId`=".$id);
        $hotelid =  substr($hotelname, 0, -1);
        $hotelidArr=explode(',',$hotelid);

        $time=date('Y-m-d H:i:s',time());
        foreach ($hotelidArr as $hidval){
            $harr=explode('/',$hidval);
            $hid=$harr[0];
            $hotel=$harr[1];
            $row=$this->model->query("INSERT INTO `h_hotelsid_areaid`( `areaId`, `hotelId`, `addtime`) VALUES ('{$id}','{$hid}','{$time}')");
        }
        $this->addStaffLog('关联酒店区域','关联酒店区域：'.$id.'--'.$hotelname,'hotelarea');

        if($row){
            unset($row);
            $this->error('更新成功！');
        }else{
            unset($row);
            $this->error('更新失败！');
        }
    }

    //区域统计
    public function  subsouArea(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=18;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);

        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }
        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid a on ii.hotelId	=a.hotelId ';
            $consql_griup=' left join h_hotelsid_areaid ii on ii.areaId=aa.id';
            $cong=" and a.adminId=".$uid;
        }else{
            $consql_g='';
            $cong='';
        }

        $sql="SELECT aa.* FROM  h_hotels_area aa ".$consql_griup.$consql_g."where aa.id>0 ".$cong." group by aa.id";
        $listGroup  =   $this->model->query($sql);
        if($listGroup){
            $this->assign("groupArr",$listGroup);
        }

        $groupname = $_GET['groupname'];
        $stime = $_GET['stime'];
        $etime = $_GET['etime'];
        $con='';

        if($stime){
            $con =$con." and  d.stime >= '".$stime."' ";
        }
        if($etime){
            $con =$con." and  d.stime <= '".$etime."' ";
        }

        $perdate=30;
        $today=date('Y-m-d',time());
        $monthNow=date('m',time());
        if($groupname&&($groupname!='all')){
            $sqlCount="SELECT count(hh.id) as hotelCount,sum(hh.clientNo+hh.clientNoPc+hh.clientNoTv) as clientTotal,sum(hh.clientNo) as clientXsNoTotal,sum(hh.clientNoPc) as clientNoPcTotal,sum(hh.clientNoTv) as clientNoTvTotal FROM `h_hotels` hh left join h_hotelsid_areaid ii on hh.id=ii.hotelId ".$consql_g." WHERE areaId=".$groupname.$cong;
//           echo $sqlCount;
            $listCount  =   $this->model->query($sqlCount);
            if($listCount){
                $this->assign("countArr",$listCount);
            }
            $listName  =   $this->model->query("SELECT areaname FROM `h_hotels_area` WHERE id=".$groupname);
            if($listName){
                $groupNamestr=$listName[0]['areaname'];
                $this->assign("titleNamestr",$groupNamestr);
            }
            $con =$con." and  ii.areaId =".$groupname;
            $sqlTotal="SELECT DATE_FORMAT(d.stime,'%m') as starttime FROM `h_hotels_data` d left join h_hotelsid_areaid ii  on d.hotelid=ii.hotelId  ".$consql_g." WHERE d.dataLevel=1 ".$con.$cong." group by starttime order by starttime desc ";
            echo $sqlTotal;
            $rowTotal =   $this->model->query($sqlTotal);

            if($rowTotal){
                $a=array_slice($rowTotal,0,12);
                $rowTotal=array_reverse($a);
                $clientTotal=$listCount[0]['clientTotal'];
                $clientXsNoTotal=$listCount[0]['clientXsNoTotal'];
                $clientNoPcTotal=$listCount[0]['clientNoPcTotal'];
                $clientNoTvTotal=$listCount[0]['clientNoTvTotal'];
                $categoriesTotal="[";
                $dataTV="{name: 'TV',data: [";
                $dataPC="{name: 'PC',data: [";
                $dataXS="{name: 'XS',data: [";
                $dataTVper="{name: 'TV',data: [";
                $dataPCper="{name: 'PC',data: [";
                $dataXSper="{name: 'XS',data: [";
                foreach($rowTotal as $var){
                    $TV=0;
                    $PC=0;
                    $XS=0;
                    $TVper=0;
                    $PCper=0;
                    $XSper=0;
                    $stime=$var['starttime'];
                    if($stime==$monthNow){
                        $perdate=date('d',time());
                    }
                    $sqlMonth="SELECT sum(d.clientNo) as clientNo,d.deviceType FROM `h_hotels_data` d left join h_hotelsid_areaid ii  on d.hotelid=ii.hotelId ".$consql_g." WHERE d.dataLevel=1 and DATE_FORMAT(d.stime,'%m')='{$stime}' ".$con.$cong."  group by d.deviceType order by d.stime asc ";
                    $rowMonth=   $this->model->query($sqlMonth);
                    if($rowMonth){
                        foreach($rowMonth as $v){
                            $clientNo=$v['clientNo'];
                            $deviceType=$v['deviceType'];
                            switch($deviceType){
                                case 'TV':$TV=$clientNo;
                                    if($clientNo){
                                        $per=round($clientNo/($perdate*$clientNoTvTotal)*100,2);
                                    }else{
                                        $per=0;
                                    }
                                    $TVper=$per;
                                    break;
                                case 'PC':$PC=$clientNo;
                                    if($clientNo){
                                        $per=round($clientNo/($perdate*$clientNoPcTotal)*100,2);
                                    }else{
                                        $per=0;
                                    }
                                    $PCper=$per;
                                    break;
                                case 'XS':$XS=$clientNo;
                                    if($clientNo){
                                        $per=round($clientNo/($perdate*$clientXsNoTotal)*100,2);
                                    }else{
                                        $per=0;
                                    }
                                    $XSper=$per;
                                    break;
                            }
                        }
                    }
                    $dataTV=$dataTV.$TV.",";
                    $dataPC=$dataPC.$PC.",";
                    $dataXS=$dataXS.$XS.",";

                    $dataTVper=$dataTVper.$TVper.",";
                    $dataPCper=$dataPCper.$PCper.",";
                    $dataXSper=$dataXSper.$XSper.",";

                    $categoriesTotal=$categoriesTotal."'".$var['starttime']."月',";
                }
            }

            $dataTV=substr($dataTV,0,-1);
            $dataTV=$dataTV."]}";
            $dataPC=substr($dataPC,0,-1);
            $dataPC=$dataPC."]}";
            $dataXS=substr($dataXS,0,-1);
            $dataXS=$dataXS."]}";

            $dataTVper=substr($dataTVper,0,-1);
            $dataTVper=$dataTVper."]}";
            $dataPCper=substr($dataPCper,0,-1);
            $dataPCper=$dataPCper."]}";
            $dataXSper=substr($dataXSper,0,-1);
            $dataXSper=$dataXSper."]}";

            $categoriesTotal=substr($categoriesTotal,0,-1);
            $categoriesTotal=$categoriesTotal."]";
            $dataTotal="[".$dataTV.",".$dataPC.",".$dataXS."]";
            $dataTotalper="[".$dataTVper.",".$dataPCper.",".$dataXSper."]";
        }else{
            $rowTotal=$listGroup;
            if($rowTotal){
                $categoriesTotal="[";
                $dataTV="{name: 'TV',data: [";
                $dataPC="{name: 'PC',data: [";
                $dataXS="{name: 'XS',data: [";
                $dataTVper="{name: 'TV',data: [";
                $dataPCper="{name: 'PC',data: [";
                $dataXSper="{name: 'XS',data: [";

                $conAll='';

                if($stime){
                    $firstday = date("Y-m-01",strtotime($stime));
                    $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
                    $conAll=" and  d.stime >= '".$firstday."' and d.stime <= '".$lastday."'";
                    $this->assign("titleNamestr",date('m月',strtotime($stime)));
                    if(date("m",strtotime($stime))==$monthNow){
                        $perdate=date('d',time());
                    }
                }else{
                    $stime=date('Y-m',time());
                    $firstday = date("Y-m-01",strtotime($stime));
                    $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
                    $conAll=" and  d.stime >= '".$firstday."' and d.stime <= '".$lastday."'";
                    $this->assign("titleNamestr",date('m月',time()));
                    if($today<$lastday){
                        $perdate=date('d',time());
                    }
                }

                foreach($rowTotal as $var){
                    $TV=0;
                    $PC=0;
                    $XS=0;
                    $TVper=0;
                    $PCper=0;
                    $XSper=0;
                    $groupNamever=$var['areaname'];
                    $groupId=$var['id'];

                    $sqlCount="SELECT sum(hh.clientNo) as clientXsNoTotal,sum(hh.clientNoPc) as clientNoPcTotal,sum(hh.clientNoTv) as clientNoTvTotal FROM `h_hotels` hh left join h_hotelsid_areaid ii on hh.id=ii.hotelId ".$consql_g." WHERE areaId=".$groupId.$cong;
                    $listCount  =   $this->model->query($sqlCount);
                    if($listCount){
                        $clientXsNoTotal=$listCount[0]['clientXsNoTotal'];
                        $clientNoPcTotal=$listCount[0]['clientNoPcTotal'];
                        $clientNoTvTotal=$listCount[0]['clientNoTvTotal'];
                    }
                    $sqlMonth="SELECT sum(d.clientNo) as clientNo,d.deviceType FROM `h_hotels_data` d left join h_hotelsid_areaid ii on d.hotelid=ii.hotelId ".$consql_g." WHERE d.dataLevel=1 and ii.areaId='{$groupId}' ".$conAll.$cong."  group by d.deviceType order by d.stime asc ";
                    $rowMonth=   $this->model->query($sqlMonth);
                    if($rowMonth){
                        foreach($rowMonth as $v){
                            $clientNo=$v['clientNo'];
                            $deviceType=$v['deviceType'];
                            switch($deviceType){
                                case 'TV':$TV=$clientNo;
                                    if($clientNo){
                                        $per=round($clientNo/($perdate*$clientNoTvTotal)*100,2);
                                    }else{
                                        $per=0;
                                    }
                                    $TVper=$per;
                                    break;
                                case 'PC':$PC=$clientNo;
                                    if($clientNo){
                                        $per=round($clientNo/($perdate*$clientNoPcTotal)*100,2);
                                    }else{
                                        $per=0;
                                    }
                                    $PCper=$per;
                                    break;
                                case 'XS':$XS=$clientNo;
                                    if($clientNo){
                                        $per=round($clientNo/($perdate*$clientXsNoTotal)*100,2);
                                    }else{
                                        $per=0;
                                    }
                                    $XSper=$per;
                                    break;
                            }
                        }
                    }
                    $dataTV=$dataTV.$TV.",";
                    $dataPC=$dataPC.$PC.",";
                    $dataXS=$dataXS.$XS.",";

                    $dataTVper=$dataTVper.$TVper.",";
                    $dataPCper=$dataPCper.$PCper.",";
                    $dataXSper=$dataXSper.$XSper.",";

                    $categoriesTotal=$categoriesTotal."'".$groupNamever."',";
                }

                $dataTV=substr($dataTV,0,-1);
                $dataTV=$dataTV."]}";
                $dataPC=substr($dataPC,0,-1);
                $dataPC=$dataPC."]}";
                $dataXS=substr($dataXS,0,-1);
                $dataXS=$dataXS."]}";

                $dataTVper=substr($dataTVper,0,-1);
                $dataTVper=$dataTVper."]}";
                $dataPCper=substr($dataPCper,0,-1);
                $dataPCper=$dataPCper."]}";
                $dataXSper=substr($dataXSper,0,-1);
                $dataXSper=$dataXSper."]}";

                $categoriesTotal=substr($categoriesTotal,0,-1);
                $categoriesTotal=$categoriesTotal."]";
                $dataTotal="[".$dataTV.",".$dataPC.",".$dataXS."]";
                $dataTotalper="[".$dataTVper.",".$dataPCper.",".$dataXSper."]";
            }
        }

        if(!$categoriesTotal){
            $categoriesTotal=0;
        }
        if(!$dataTotal){
            $dataTotal=0;
        }
        if(!$dataTotalper){
            $dataTotalper=0;
        }
        //echo $categoriesTotal;
        //        echo $dataTotal;
        //        exit;
        $this->assign("dataTotalper",$dataTotalper);
        $this->assign("categoriesTotal",$categoriesTotal);
        $this->assign("dataTotal",$dataTotal);

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['subsouArea']);
        $this->display("admin/subsouArea");
    }

    //特殊用户管理
    public function hotelUser(){
        require(CP_PATH.'ext/Page.class.php');
        //获取页数ID
        $page_id=intval($_GET['page']);
        $name = $_GET['groupname'];
        if($name){
            $con=" where aa.username like '%".$name."%' ";
        }

        $url=__URL__.'/page?page='.$page_id;
        $page=new Page();
        //每页显示行数
        $listRows=10;//每页显示的信息条数
        //每页显示页数
        $pageBarNum=5;
        $cur_page=$page->getCurPage($url);
        $limit_start=($cur_page-1)*$listRows;
        $limit=$limit_start.','.$listRows;
        $limitStr='';
        if($limit!=''){
            $limitStr = " limit ".$limit;
        }

//        $count=$this->model->table('h_hotelsid_adminid')->where($condition)->count();
        $sql = "select aa.username,ii.* from h_hotelsid_adminid ii left join h_admin aa on ii.adminId=aa.id group by ii.adminId ".$con.$limitStr;
        $list  =   $this->model->query($sql);

        if($list){
            $count=count($list);
            $this->assign('count',$count);
            if($listRows>=$count){
                $this->assign('page','');
            }else{
                $this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
            }
            $hotel='';
            $listsArry=array();
            foreach($list as $v){
                $username=$v['username'];
                $userid=$v['adminId'];
                $listHotel  =   $this->model->query("SELECT hh.hotel,hh.id FROM `h_hotelsid_adminid` ii left join h_hotels hh on hh.id=ii.`hotelId` WHERE `adminId`=".$userid);
                $hotel='';
                foreach($listHotel as $h){
                    $hotel=$hotel.$h['id'].'/'.$h['hotel'].',';
                }
                $listArry=array('username'=>$username,'userid'=>$userid,'hotel'=>$hotel);
                array_push($listsArry,$listArry);
            }
        }

        if(count($list)){
            $this->assign("roomArr",$listsArry);
        }
        $listAdmin =   $this->model->query("SELECT a.* FROM `h_permission` p left join h_admin a on p.`id`=a.level WHERE p.`rolename`='统计'");
        $this->assign("adminArr",$listAdmin);
        $this->hotelSelect();
        unset($row);
        unset($list);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['hotelUser']);
        $this->display("admin/hotelUser");
    }

    //关联酒店、区域
    public function join_hotel_admin(){
        $hotelname = $_POST['hotelname'];
        $areaid = $_POST['areaname'];
        $time=time();
        $id = $_POST['areaid'];
        if(!$hotelname){
            $this->error('酒店名不能为空！');
        }

        $this->model->query("DELETE FROM `h_hotelsid_adminid` WHERE `adminId`=".$id);
        $hotelid =  substr($hotelname, 0, -1);
        $hotelidArr=explode(',',$hotelid);

        $time=date('Y-m-d H:i:s',time());
        foreach ($hotelidArr as $hidval){
            $harr=explode('/',$hidval);
            $hid=$harr[0];
            $hotel=$harr[1];
            $row=$this->model->query("INSERT INTO `h_hotelsid_adminid`( `adminId`, `hotelId`, `addtime`) VALUES ('{$areaid}','{$hid}','{$time}')");
        }
//        $this->addStaffLog('关联酒店区域','关联酒店区域：'.$id.'--'.$hotelname,'hotelarea');

        if($row){
            unset($row);
            $this->error('更新成功！');
        }else{
            unset($row);
            $this->error('更新失败！');
        }
    }

    //酒店区域删除
    public function delallhotelAdmin(){
        $msg = 1;

        $ids = $_POST['arr'];
        $ids =  substr($ids, 0, -1);
        $strArr=explode(',',$ids);
        $username='';
        foreach ($strArr as $val){
            $sql = "delete from h_hotelsid_adminid where adminId=".$val ;
            $row = $this->model->query($sql);
        }
//        $this->addStaffLog('删除酒店区域','删除酒店区域：'.$username,'hotelarea');
        $json ='{"msg":"'.$row.'"}';
        unset($row);
        echo $json;
        exit;
    }
    
    /*酒店运维信息
     * mc 2016年11月26日
     */
    public function operationData(){
    	if(!isset($_SESSION['manage_uid'])){
    		$this->display("index/login");
    		exit;
    	}
    	require(CP_PATH.'ext/Page.class.php');
    	//获取页数ID
    	$page_id=intval($_GET['page']);
    	$rname = $_GET['rname'];
    	if($rname){
    		$keyCon = "  WHERE  h.hotel LIKE '%".$rname."%' ";
    		$con ="  WHERE  `hotel` LIKE '%".$rname."%' ";
    		$andCon = " AND h.hotel LIKE '%".$rname."%' ";
    	}
    	$url=__URL__.'/page?page='.$page_id;
    	$page=new Page();
    	//每页显示行数
    	$listRows=20;//每页显示的信息条数
    	//每页显示页数
    	$pageBarNum=5;
    	$cur_page=$page->getCurPage($url);
    	
    	$limit_start=($cur_page-1)*$listRows;
    	$limit=$limit_start.','.$listRows;
    	$limitStr='';
    	if($limit!=''){
    		$limitStr = " LIMIT ".$limit;
    	}
    	$adminId = $_SESSION['manage_uid'];
    	if($adminId==1){
    		$countsql = 'SELECT COUNT(*) AS zs FROM `h_hotels`'.$con;
    		$hotelsql = 'SELECT * FROM `h_hotels`'.$con.' ORDER BY `rstate` DESC,`id` ASC  '.$limitStr;
    	}else{
	    	$countsql = 'SELECT COUNT(*) AS zs FROM  `h_hotels` h LEFT JOIN  `h_hotelsid_adminid` ha ON ha.hotelId = h.id LEFT JOIN h_admin a ON a.id = ha.adminId WHERE a.id = '.$adminId.$keyCon;
    		$hotelsql = 'SELECT h.* FROM  `h_hotels` h LEFT JOIN  `h_hotelsid_adminid` ha ON ha.hotelId = h.id LEFT JOIN h_admin a ON a.id = ha.adminId WHERE a.id = '.$adminId.$andCon.' ORDER BY h.rstate DESC,h.id ASC  '.$limitStr;
    	}
	   	$row = $this->model->query($countsql);
    	if ($row){
    		$count = $row[0][zs];
    	}
    	$list = $this->model->query($hotelsql);
    	if ($list){
    		$this->assign('count',$count);
    		$this->assign("hotelArr",$list);
    		if($listRows>=$count){
    			$this->assign('page','');
    		}else{
    			$this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
    		}
    	}
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['operationData']);
    	$this->display("admin/operationData");
    }
    /**
     * 获取酒店最新运维数据
     * mc@2016年11月30日
     */
    public function getOperation(){
    	if(isset($_POST['hotelId'])){
    		$hotelId = $_POST['hotelId'];
    	}else{
    		echo json_encode(array('result'=>false,'msg'=>'输入信息错误'));
    	}
    	$list = $this->model->query('SELECT * FROM `h_operation` WHERE `hotelId` = '.$hotelId);
    	if(!$list){
    		echo json_encode(array('result'=>false,'msg'=>'暂无数据'));
    		exit;
    	}
    	$operlist = explode(';',$list[0]['data']);
    	$strtime = date('Y-m-d H:i:s',$list[0]['addtime']);
    	//警报列表
    	$noticeArr = array();
    	$noticelist = $this->model->query('SELECT * FROM `h_canshu` WHERE `name` = "operation_'.$hotelId.'" OR `name`="operation_0" ORDER BY `name`');
    	if($noticelist){
    		for($i=0;$i<count($noticelist);$i++){
    			$newkey = trimall($noticelist[$i]['x']);
    			$noticeArr[$newkey] = explode("@@", $noticelist[$i]['y']);
    		}
    	}
    	$html = '';
    	$excelData = array();
    	$excelflag = $excelmerge = 1;
    	foreach($operlist as $key=>$val){
    		$valtmp = explode(',', trim(strstr($val,'@@'),'@@'));
    		if(is_array($valtmp)){
    			$keyword = strstr($val,'@@',true);
    			for($i=0;$i<count($valtmp);$i++){
    				$name = strstr($valtmp[$i],':',true);
    				$lowername = trimall($name);
    				if(!$name){
    					continue;
    				}
    				$value = trim(strstr($valtmp[$i],':'),':');

    				if(strpos($value, '%')){
    					$runValue = (float)$value/100;
    				}else if(strpos($value,'/')){
    					$runValue = strstr($value,'/',true)/trim(strstr($value,'/'),'/');
    				}else{
    					$runValue = $value;
    				}
    				
    				switch (matchname($lowername)){
    					case 'cpuload':
    						$runValue = max(explode(' ',$value));
    						break;
    					case 'storage':
    						$value = storename($value);
    						break;
    					case 'systemuptime':
    						$value = Sec2Time($value);
    						break;
    				}
    				
    				
    				$notice = '';
    				if($lowername=='web'||$lowername=='mysql'){
    					if(strlen($value)>1){
    						$runValue = max(explode(' ',$value));
    					}
    					$value='正常';
    					if($runValue>0){
    						$notice = 'style="background:#FCD0C3;"';
    						$value='异常';
    					}
    				}
    				
    				
    				//判断警报值 
    				if(array_key_exists($lowername, $noticeArr)){
	    				switch ($noticeArr[$lowername][0]){
	    					//1:>=,2:<=
	    					case 1:
	    						if($runValue>=$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#FF0000;"';
	    							//发送短信
	    						}elseif($runValue>=0.9*$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#FF8C00;"';
	    						}elseif($runValue>=0.8*$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#FFFF00;"';
	    						}elseif($runValue>=0.7*$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#00BFFF;"';
	    						}
	    						break;
	    					case 2:
	    						if($runValue<=$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#FF0000;"';
	    							//发送短信
	    						}elseif($runValue<=1.1*$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#FF8C00;"';
	    						}elseif($runValue<=1.2*$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#FFFF00;"';
	    						}elseif($runValue<=1.3*$noticeArr[$lowername][1]){
	    							$notice = 'style="background:#00BFFF;"';
	    						}
	    						break;
	    				}
	    			}
    				$excelflag++;
    				$excelData['data']['A'.$excelflag] = $keyword;
    				$excelData['data']['B'.$excelflag] = $name;
    				$excelData['data']['C'.$excelflag] = $value;
    				//生成表格
    				if($i==0){
    					$excelmerge++;
    					$html.="<tr class='ctt_gr'><td class='td_head' rowspan=".count($valtmp).">".$keyword."</td><td ".$notice." class='con_td' id='".$key.$i."name'>".$name."</td><td ".$notice." class='con_td' id='".$key.i."'>".$value."</td></tr>";
    					if(count($valtmp)>1){
    						$excelAkey = 'A'.$excelmerge;
    						$excelmerge = $excelmerge + count($valtmp) - 1;
    						$excelAkey.=':A'.$excelmerge;
    						$excelData['merge'][]=$excelAkey;
    					}
    				}else{
    					$html.="<tr class='ctt_gr'><td ".$notice." class='con_td' id=".$key.$i."name'>".$name."</td><td ".$notice." class='con_td' id='".$key.$i."'>".$value."</td></tr>";
    				}
    			}
    			
    		}
    	}
    	//房间信息处理
    	$roomlist = $this->model->query('select count(*) as rn from `h_roomstate` where `rstate`=1 and `hotelId` = '.$hotelId);
    	if($roomlist[0][rn]){
    		$roomnum = $roomlist[0][rn];
    	}else{
    		$roomnum = 0;
    	}
    	$onlinelist = $this->model->query('select * from `h_roomstate` where `hotelId` = '.$hotelId);
    	if($onlinelist){
    		$k=0;
    		for($i=0;$i<count($onlinelist);$i++){
    			if($onlinelist[$i]['stime']&&(time()-strtotime($onlinelist[$i]['stime'])<=300)){
    				$k++;
    			}else{
    				continue;
    			}
    		}
    		$onlinenum = $k;
    	}else{
    		$onlinenum = 0;
    	}
    	$html.="<tr class='ctt_gr'><td class='td_head' rowspan=2>房间信息</td><td class='con_td' >开房数量</td><td class='con_td'>".$roomnum."</td></tr>";
    	$html.="<tr class='ctt_gr'><td class='con_td' >在线数量</td><td class='con_td'>".$onlinenum."</td></tr>";
    	$excelflag++;
    	$excelData['data']['A'.$excelflag] = '房间信息';
    	$excelData['data']['B'.$excelflag] = '开房数量';
    	$excelData['data']['C'.$excelflag] = $roomnum;
    	$excelflag++;
    	$excelData['data']['A'.$excelflag] = '房间信息';
    	$excelData['data']['B'.$excelflag] = '在线数量';
    	$excelData['data']['C'.$excelflag] = $onlinenum;
    	$excelAkey = 'A'.($excelmerge+1).':A'.($excelmerge+2);
    	$excelData['merge'][]=$excelAkey;
    	
    	$data = array(
    		'strtime' => $strtime,
    		'strhtml' => $html,
    		'excelData'=>$excelData
    	);
    	echo json_encode(array('result'=>true,'msg'=>$data));
    	exit;
    }
    public function operationNotice(){
    	$adminId = $_SESSION['manage_uid'];
    	if($adminId==1){
    		$hotelsql = 'SELECT * FROM `h_hotels` ORDER BY `id` ';
    	}else{
    		$hotelsql = 'SELECT h.* FROM  `h_hotels` h LEFT JOIN  `h_hotelsid_adminid` ha ON ha.hotelId = h.id LEFT JOIN h_admin a ON a.id = ha.adminId WHERE a.id = '.$adminId.' ORDER BY h.id ';
    	}
    	$hotels = $this->model->query($hotelsql);
    	if($hotels){
    		foreach($hotels as $hotel){
    			$hotelids[] = $hotel['id'];
    		}
    		$this->assign('hotels', $hotels);
    		if(isset($_GET['hotelId'])&&in_array($_GET['hotelId'], $hotelids)){
    			$hotelId = $_GET['hotelId'];
    		}else{
    			$hotelId = $hotelids[0];
    		}
    		$this->assign('hotelId', $hotelId);
    	}
    	$noticelist = $this->model->query('SELECT * FROM `h_canshu` WHERE `name` = "operation_'.$hotelId.'" OR `name` = "operation_0" ORDER BY `name`');
    	$noticeArr = array();
    	if($noticelist){
    		for($i=0;$i<count($noticelist);$i++){
    			$matchtmp = explode("@@", $noticelist[$i]['y']);
    			switch ($matchtmp[0]){
    				case 1:
    					$value = '>='.$matchtmp[1];
    					break;
    				case 2:
    					$value = '<='.$matchtmp[1];
    					break;
    			}
    			$noticeArr[$noticelist[$i]['x']] = array(
    				'id' => $noticelist[$i]['id'],
    				'value'	=> $value,
    				'name' => (int)substr($noticelist[$i]['name'],10)
    			);
    		}
    		$this->assign('noticeArr', $noticeArr);
    	}
    	$list = $this->model->query('SELECT * FROM `h_operation` WHERE `hotelId`='.$hotelId.' ORDER BY `id` DESC LIMIT 1');
    	if($list){
    		$namelist=array();
    		foreach(explode(';', $list[0]['data']) as $key=>$val){
    			$valtmp = explode(',', trim(strstr($val,'@@'),'@@'));
    			if(is_array($valtmp)){
    				for($i=0;$i<count($valtmp);$i++){
    					$name = strstr($valtmp[$i],':',true);
    					if(!$name||$noticeArr[$name]['name']>0||strpos(trimall($name), 'uptime')!==false||strpos(trimall($name), 'web')!==false||strpos(trimall($name), 'mysql')!==false){
    						continue;
    					}
    					$namelist[] = $name;
    				}
    			}
    		}
    		$this->assign('namelist', $namelist);
    	}
    	$this->assign('appselect',$adminId);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['operationNotice']);
    	$this->display('admin/operationNotice');
    }
    public function addOperNotice(){
    	if(!isset($_POST['hotelId'])||!isset($_POST['x'])||!isset($_POST['symbol'])||!isset($_POST['number'])){
    		echo json_encode(array(
    			'result'=>false,
    			'msg' =>'信息不完善'
    		));
    		exit;
    	}
    	extract($_POST);
    	$name = trim($name);
    	if(!is_numeric($number)){
    		echo json_encode(array(
    			'result'=>false,
    			'msg' => '报警值只支持数字',
    		));
    		exit;
    	}
    	$list = $this->model->query('select * from `h_canshu` where `name` = "operation_'.$hotelId.'" and `x`="'.$x.'"');
    	if($list){
    		echo json_encode(array(
    				'result'=>false,
    				'msg' => '已经存在该参数，请先删除',
    		));
    		exit;
    	}
    	$this->model->query('INSERT INTO `h_canshu` (`name`,`x`,`y`) VALUES ("operation_'.$hotelId.'","'.$x.'","'.$symbol.'@@'.$number.'")');
    	$insertId = $this->model->insert_id();
    	if($insertId){
    		echo json_encode(array(
    				'result'=>true,
    				'msg' => '保存成功',
    		));
    		exit;
    	}else{
    		echo json_encode(array(
    				'result'=>false,
    				'msg' => '保存失败，请重新添加',
    		));
    		exit;
    	}
    	
    }
    public function deleteOperNotice(){
    	if(!isset($_POST['id'])){
    		echo json_encode(array('result'=>false));
    		exit;
    	}
    	$id = $_POST['id'];
    	$sql = 'delete from `h_canshu` where `id` ='.$id;
    	$this->model->query($sql);
    	echo json_encode(array('result'=>true));exit;
    }
    public function operationDefault(){
    	$list = $this->model->query('select * from `h_operation` order by `id` desc limit 1');
		$datalist = array();
		if($list){
			$data = explode(';', $list[0]['data']);
			foreach($data as $value){
				if(stripos($value, 'uptime')!==false||stripos($value, 'web')!==false||stripos($value, 'mysql')!==false){
					continue;
				}
				$valtmp = explode(',', trim(strstr($value,'@@'),'@@'));
				foreach($valtmp as $val){
					$datalist[strstr($val, ":",true)] = array('','');
				}
			}
		}
		$existlist = $this->model->query("select * from `h_canshu` where `name`='operation_0'");
		$exists = array();
		if($existlist){
			foreach($existlist as $value){
				$exists[$value['x']] = explode("@@", $value['y']);
			}
		}
		$standlist = array_merge($datalist,$exists);
		$this->assign('noticeArr', $standlist);
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['operationDefault']);
    	$this->display("admin/operationNotice_0");
    }
    public function addDefaultOper(){
    	if(!isset($_POST['key'])||!isset($_POST['symbol'])||!isset($_POST['number'])){
    		echo json_encode(array(
    				'result'=>false,
    				'msg' =>'信息不完善'
    		));
    		exit;
    	}
    	if(!is_numeric($_POST['number'])){
    		echo json_encode(array(
    				'result'=>false,
    				'msg' => '报警值只支持数字',
    		));
    		exit;
    	}
    	$list = $this->model->query('select * from `h_canshu` where `name` = "operation_0" and `x`="'.$_POST['key'].'"');
		$y = $_POST['symbol'].'@@'.$_POST['number'];
    	if($list){
    		$this->model->query('update `h_canshu` set `y` = "'.$y.'" where `name`="operation_0" and `x`="'.$_POST['key'].'"');
    	}else{
    		$this->model->query('INSERT INTO `h_canshu` (`name`,`x`,`y`) VALUES ("operation_0","'.$_POST['key'].'","'.$y.'")');
    	}
    	echo json_encode(array(
    		'result'=>true,
    		'msg' => '修改成功',
    	));
    	exit;
    	 
    }
    public function clearDefaultOper(){
    	if(!isset($_POST['key'])){
    		echo json_encode(array(
    			'result'=>false,
    			'msg' => '不合法',
    		));
    		exit;
    	}
    	$key = $_POST['key'];
    	$rows = $this->model->table('h_canshu')->where('`name`="operation_0" and `x` = "'.$key.'"')->delete();
    	
    	if($rows){
    		echo json_encode(array(
    			'result'=>true,
    			'msg' => '成功',
    		));
    		exit;
    	}else{
    		echo json_encode(array(
    			'result'=>false,
    			'msg' => '清空失败',
    		));
    		exit;
    	}
    }
    public function outputOperation(){
    	ob_end_clean();
    	header("content-type:text/html;charset=utf8");
    	/** Error reporting */
    	error_reporting(E_ALL);
    	/** PHPExcel */
    	include_once cpApp_PATH.'/../ext/PHPExcel.php';
    	/** PHPExcel_Writer_Excel2003用于创建xls文件 */
    	include_once cpApp_PATH.'/../ext/PHPExcel/Writer/Excel5.php';
    	
    	// Create new PHPExcel object
    	$objPHPExcel = new PHPExcel();
    	// Set properties
    	$objPHPExcel->getProperties()->setCreator("Ehotel");
    	//$objPHPExcel->getProperties()->setLastModifiedBy("Ehotel");
    	$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
    	$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
    	$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
    	$excelData=json_decode($_POST['postTable'],true);
    	$excelHead = $_POST['postTableHead'];
    	if(!$excelData||!$excelHead){
    		header("Content-type: text/html; charset=utf8");
    		echo"<script>alert('暂无数据');history.go(-1);</script>";
    		exit;
    	}
    	$objPHPExcel->getActiveSheet()->SetCellValue("A1",$excelHead);
    	$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
    	$objPHPExcel->getActiveSheet()->getStyle("A1")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle("A1")->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
    	$objPHPExcel->getActiveSheet()->mergeCells("A1:C1");
    	foreach($excelData['data'] as $key=>$value){
    		$objPHPExcel->getActiveSheet()->SetCellValue($key,$value);
    		if(strpos($key, "A")!==false){
    			$objPHPExcel->getActiveSheet()->getStyle($key)->getFont()->setBold(true);
    		}
    		$objPHPExcel->getActiveSheet()->getStyle($key)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    		$objPHPExcel->getActiveSheet()->getStyle($key)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
    	}
    	foreach($excelData['merge'] as $value){
    		$objPHPExcel->getActiveSheet()->mergeCells($value);
    		$value0 = strstr($value,':',true);
    		$objPHPExcel->getActiveSheet()->getStyle($value0)->getFont()->setBold(true);
    		//左右、上下居中
    		$objPHPExcel->getActiveSheet()->getStyle($value0)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    		$objPHPExcel->getActiveSheet()->getStyle($value0)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
    	}
    	$objPHPExcel->setActiveSheetIndex(0);
    	$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
    	$objPHPExcel->getActiveSheet()->getColumnDimension("B")->setAutoSize(true);
    	$objPHPExcel->getActiveSheet()->getColumnDimension("C")->setAutoSize(true);
    	// Rename sheet
    	$name = 'Ehotel-'.uniqid().$_SESSION['manage_uid'];
    	$objPHPExcel->getActiveSheet()->setTitle($name);
    	// Save Excel 2007 file
    	//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
    	unset($list);
    	$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
    	$objWriter->save(str_replace('.php', '.xls', __FILE__));
    	header("Pragma: public");
    	header("Expires: 0");
    	header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
    	header("Content-Type:application/force-download");
    	header("Content-Type:application/vnd.ms-execl");
    	header("Content-Type:application/octet-stream");
    	header("Content-Type:application/download");
    	header("Content-Disposition:attachment;filename=".$name.".xls");
    	header("Content-Transfer-Encoding:binary");
    	$objWriter->save("php://output");
    }

//数据导出
    public function exportData($headArry,$exportDataArry){
        require(CP_PATH.'ext/PHPExcel.php');
        require(CP_PATH.'ext/PHPExcel/Writer/Excel5.php');
        require(CP_PATH.'ext/PHPExcel/Writer/Excel2007.php');
        error_reporting(E_ALL);
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array('memoryCacheSize'=>'16MB');
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
        $objPHPExcel = new PHPExcel();
        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("cj")
            ->setLastModifiedBy("cj")
            ->setTitle("数据EXCEL导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");

        $styleThinBlackBorderOutline = array(
            'borders' => array (
                'outline' => array (
                    'style' => PHPExcel_Style_Border::BORDER_THIN,  //设置border样式
                    //'style' => PHPExcel_Style_Border::BORDER_THICK, 另一种样式
                    'color' => array ('argb' => 'FF000000'),     //设置border颜色
                ),
            ),
        );
        $cellNum=0;
        // 表头
        foreach($headArry as $k=>$v){
            $cellNum++;
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue($k.'1', $v);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($k)->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle($k.'1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle($k.'1')->getFill()->getStartColor()->setARGB("#0cedffb");
            $objPHPExcel->getActiveSheet()->getStyle($k.'1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $objPHPExcel->getActiveSheet()->getStyle($k.'1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->getActiveSheet()->getStyle($k.'1')->applyFromArray($styleThinBlackBorderOutline);
        }
        $objPHPExcel->setActiveSheetIndex(0)->getRowDimension(1)->setRowHeight(35);

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        foreach($exportDataArry as  $keyNum=>$ver){
            foreach($ver as $key=>$data){
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue($key, $data);
                $objPHPExcel->getActiveSheet()->getStyle($key)->applyFromArray($styleThinBlackBorderOutline);
//                $objPHPExcel->getActiveSheet()->getStyle($key)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//                $objPHPExcel->getActiveSheet()->getStyle($key)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            }
            $keyNum=$keyNum+2;
            $objPHPExcel->setActiveSheetIndex(0)->getRowDimension($keyNum)->setRowHeight(20);
        }

        $objPHPExcel->getActiveSheet()->setTitle('data');
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="数据导出_'.date("YmdHis").'.xls"');
        header('Cache-Control: max-age=0');
        ob_clean();//关键
        flush();//关键
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        unset($data);
        unset($objPHPExcel);
        exit;
    }
    
    //管理email地址
    public function emailManage(){
    	require(CP_PATH.'ext/Page.class.php');
    	$page_id=intval($_GET['page']);
    	$url=__URL__.'/page?page='.$page_id;
    	$page=new Page();
    	//每页显示行数
    	$listRows=10;//每页显示的信息条数
    	//每页显示页数
    	$pageBarNum=5;
    	$cur_page=$page->getCurPage($url);
    
    	$limit_start=($cur_page-1)*$listRows;
    	$limit=$limit_start.','.$listRows;
    	$limitStr='';
    	$con = 'where `state`=0';
    	if(isset($_GET['soname'])){
    		$con.=' and `name` like "%'.$_GET['soname'].'%"';
    	}
    	if($limit!=''){
    		$limitStr = " limit ".$limit;
    	}
    
    	$sqlcount = "select count(*) as zs from `h_emaillist` ".$con;
    	$row = $this->model->query($sqlcount);
    	if ($row){
    		$count = $row[0][zs];
    	}
    	$sql = "SELECT * FROM `h_emaillist` ".$con;
    	$list  =   $this->model->query($sql);
    	if ($list){
    		$this->assign('count',$count);
    		$this->assign("contents",$list);
    		if($listRows>=$count){
    			$this->assign('page','');
    		}else{
    			$htmPage =  $page-> show($url,$count,$listRows,$pageBarNum,$mode=5);
    			$this->assign('page', $htmPage);
    		}
    	}
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['emailManage']);
    	$this->display('admin/emailManage');
    }
    //删除多条信息
    public function deleteAllEmail(){
    	$ids = $_POST['arr'];
    	$ids =  substr($ids, 0, -1);
    	$strArr=explode(',',$ids);
    	foreach ($strArr as $val){
    		$sql = "UPDATE `h_emaillist` SET state=1 where id='".$val."'";
    		$row = $this->model->query($sql);
    	}
    	echo json_encode(array('result'=>true,'msg'=>'添加成功'));
    	exit;
    }
    //增加一条信息
    public function addEmailList(){
    	$name = $_POST['name'];
    	$address = $_POST['address'];
    	$subject = $_POST['subjectType'];
    	if(!$name||!$address){
    		echo json_encode(array('result'=>true,'msg'=>'信息不完善'));
    		exit;
    	}
    	$sql = 'INSERT INTO `h_emaillist` (`name`,`address`,`subject`,`state`) VALUES ("'.$name.'","'.$address.'","'.$subject.'",0)';
    	$row = $this->model->query($sql);
    	if($row){
    		echo json_encode(array('result'=>true,'msg'=>'添加成功'));
    		exit;
    	}
    }
    //酒店地图分布
    public function hinfoAll(){
    	$adminGroup=$this->isSpecialAdmin();
    	if($adminGroup){
    		$uid=$_SESSION['manage_uid'];
    		$consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
    		$cong=" and a.adminId=".$uid;
    	}else{
    		$consql_g='';
    		$cong='';
    	}
    
    	$sql = "select h.*,hc.cityName from h_hotels h  ".$consql_g." left join h_citys hc on LEFT( h.citycode, 2)=hc.assign where 1 ".$cong." order by h.id";
    	$list  =   $this->model->query($sql);
    	$onlinelist  = array();
    	$offlinelist  = array();
    	$time = time();
    	$pronums = array();
    	if ($list){
    		foreach($list as $key=>$hotel){
    			if(($time-$hotel['stime'])<900){
    				$onlinelist[] = array('name'=>$hotel['hotel'],'value'=>$hotel['cityName'],'geoCoord'=>array($hotel['lng']/100000000,$hotel['lat']/100000000));
    				$list[$key]['timestate']=0;
    				$pronums[$hotel['cityName']]['on']++;
    			}else{
    				$offlinelist[] = array('name'=>$hotel['hotel'],'value'=>$hotel['cityName'],'geoCoord'=>array($hotel['lng']/100000000,$hotel['lat']/100000000));
    				$list[$key]['timestate']=1;
    				$pronums[$hotel['cityName']]['off']++;
    			}
    		}
    		$this->assign("roomArr",$list);
    	}
    	$this->assign('pronums',json_encode($pronums));
    	$this->assign('totalnum', count($list));
    	//$prosql = 'SELECT hc.cityName as name, COUNT(*)-1 AS value FROM  `h_citys` hc LEFT JOIN  `h_hotels` hh ON hc.assign = LEFT( hh.citycode, 2) WHERE hc.depth =1 GROUP BY hc.assign ORDER BY hc.assign'; //未处理用户权限   	
    	//$prolist = $this->model->query($prosql);
    	//$prosql = "select hc.cityName as name,count(*) as value from h_hotels h ".$consql_g.$con.$cong." left join h_citys hc on h.citycode=hc.assign group by hc.assign order by h.id ";
    	$this->assign('onlinelist',json_encode($onlinelist));
    	$this->assign('offlinelist',json_encode($offlinelist));
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['hinfoAll']);
    	$this->display("admin/hinfoAll");
    }
    //修改email数据
    public function modifyEmail(){
    	$id = $_POST['id'];
    	$type = $_POST['type'];
    	$value = $_POST[$type];
    	$sql = 'update `h_emaillist` set `'.$type.'` = "'.$value.'" where `id` = '.$id;
    	$flag = $this->model->query($sql);
    	if($flag){
    		echo json_encode(array('result'=>true,'msg'=>'添加成功'));
    		exit;
    	}else{
    		echo json_encode(array('result'=>false,'msg'=>'添加失败'));
    		exit;
    	}
    }

    //统计检索区域
    public function searchCondition(){
        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql_g=' left join h_hotelsid_adminid ha on h.id=ha.hotelId ';
            $cong=" and ha.adminId=".$uid;
        }else{
            $consql_g='';
            $cong='';
        }
        //去除测试酒店
        $hotels = $this->model->query('select h.id,h.hotel from h_hotels h '.$consql_g.' where h.hotel NOT LIKE  "%测试%"'.$cong);//所有酒店
        for($i=count($hotels);$i>0;$i--){
            $hotels[$i] = $hotels[$i-1];
        }
        $hotels[0] = array('id'=>'all','hotel'=>'所有酒店');
        $groups = $this->model->query('SELECT h.groupId,hg.groupname FROM h_hotels h '.$consql_g.' LEFT JOIN  `h_hotels_group` hg ON hg.id = h.groupId where h.hotel NOT LIKE  "%测试%" '.$cong.' GROUP BY h.groupId');
        for($i=count($groups);$i>0;$i--){
            if(!$groups[$i-1]['groupId']){
                $groups[$i]['groupname'] = '无所属';
                $groups[$i]['groupId'] = $groups[$i-1]['groupId'];
            }else{
                $groups[$i] = $groups[$i-1];
            }
        }
        $groups[0] = array('groupId'=>'all','groupname'=>'所有集团');
        $totalxs = $this->model->query('select SUM(clientNo) as totalxs from h_hotels h '.$consql_g.' where 1'.$cong);
        $totalpc = $this->model->query('select SUM(clientNoPc) as totalpc from h_hotels h '.$consql_g.' where 1'.$cong);
        $totaltv = $this->model->query('select SUM(clientNoTv) as totaltv from h_hotels h '.$consql_g.' where 1'.$cong);
        $totalRooms = array(
            'all'=>$totalxs[0]['totalxs']+$totalpc[0]['totalpc']+$totaltv[0]['totaltv'],
            'XS' =>$totalxs[0]['totalxs'],
            'PC' =>$totalpc[0]['totalpc'],
            'TV' =>$totaltv[0]['totaltv'],
        );
        $this->assign('totalRooms', json_encode($totalRooms));
        $this->assign('hotels', $hotels);
        $this->assign('groups', $groups);
    }
    /*
     * 2017年1月21日 15:12:12
     * mc酒店入住情况-测试用
     */
    public function countcheckin(){
        $this->searchCondition();
    	$this->assign('left', 'admin_countcheckin');
    	$this->display('admin/countcheckin');
    }
    /*
     * 执行数据处理
     */
    public function getCountHotels(){
    	if(!isset($_POST['datas'])){
    		echo json_encode(array('result'=>false,'msg'=>'查询失败'));
    		exit;
    	}
    	$adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql['g'] = ' left join h_hotelsid_adminid ha on hd.hotelid=ha.hotelId ';
            $con['g'] = " and hd.dataLevel=1 and ha.adminId=".$uid;
            $consql['h'] = ' left join h_hotelsid_adminid ha on h.id=ha.hotelId ';
            $con['h'] = " and ha.adminId=".$uid;
            $consql['movie'] = ' left join h_hotelsid_adminid ha on hd.hotelid=ha.hotelId ';
            $con['movie'] = " and ha.adminId=".$uid;
        }else{
            $con['h'] = $consql['h'] = $consql['g'] =$consql['movie']= $con['movie'] ='';
            $con['g']=' and hd.dataLevel=1';
        }
    	$datas = $_POST['datas'];
    	$datas['clientNo'] = json_decode($datas['clientNo'],true);
    	$datas['flagTypes'] = array('XS'=>'clientNo','PC'=>'clientNoPc','TV'=>'clientNoTv');
    	$tabledatas = array();
    	if($datas['month']==0){
    		$datas['startDate'] = date('Y-m-d',strtotime($datas['sdate']));
    		$datas['endDate'] =date('Y-m-d',strtotime( $datas['edate'] ));
    	}else{
    		$datas['startDate'] = date('Y-m-01',strtotime("-".$datas['month']." month"));
    		$datas['endDate'] = date('Y-m-d',strtotime($datas['startDate']." +".$datas['month']." month -1 day"));
    	}
    	if($datas['deviceType']!='all'){
    		$con['g'].= ' and deviceType = "'.$datas['deviceType'].'"';
    	}
        $consql['g'].=' left join h_hotels h on hd.hotelid=h.id';
        $consql['movie'].=' left join h_hotels h on hd.hotelid=h.id';
        $titleStr='';
    	if($datas['groupId']!='all'){
    		$con['g'].=' and h.groupId='.$datas['groupId'];
            $con['h'].=' and h.groupId='.$datas['groupId'];
            $con['movie'] .=' and h.groupId='.$datas['groupId'];
            $titleStr=$datas['groupName'].' ';
    	}
    	if($datas['cate']==1){
    		$hotelDatas = $this->doccin_rant($datas, $consql, $con);
    		$title = $titleStr.' 酒店入住率排行';
    	}else{
    		if($datas['hotelId']!='all'){
                $con['h'].=' and h.id='.$datas['hotelId'];
    			$con['g'] .=' and hd.hotelid = '.$datas['hotelId'];
                $con['movie'] .=' and hd.hotelid = '.$datas['hotelId'];
    			$hotelClientNo = $this->model->query('select * from h_hotels where id='.$datas['hotelId']);
    			if(!$hotelClientNo){
    				$hotelClientNo=array('clientNoTv'=>0,'clientNoPc'=>0,'clientNo'=>0);
    			}
    			if($datas['deviceType']=='all'){
    				$nums = $hotelClientNo[0]['clientNoTv']+$hotelClientNo[0]['clientNoPc']+$hotelClientNo[0]['clientNo'];
    			}else{
    				$nums = $hotelClientNo[0][$datas['flagTypes'][$datas['deviceType']]];
    			}
                $titleStr.=$datas['hotelName'].' ';
    		}else{
    			$nums = $datas['clientNo'][$datas['deviceType']];
    			$list = '';
    		}

            if($datas['cate']==3){
                $tabledatas = $this->doccin_targetStatistics($datas, $consql, $con);
                $monthCon= date('Y-m',strtotime($datas['startDate']));
                $title = $monthCon.' '.$titleStr.' 酒店目标统计列表';
            }elseif($datas['cate']==5){
                if($datas['month']==1){
                    $datas['startDate'] = date('Y-m-01', strtotime(date("Y-m-d")));
                    $datas['endDate'] =date("Y-m-d",strtotime("-1 day")) ;
                }
                $title =$titleStr. ' 酒店入住日常';
                $hotelDatas = $this->doccin_dailyCount($datas, $consql, $con);
            }elseif($datas['cate']==6){
                //行为统计数据
                if($datas['month']==1){
                    $datas['startDate'] = date('Y-m-01', strtotime(date("Y-m-d")));
                    $datas['endDate'] =date("Y-m-d",strtotime("-1 day")) ;
                }
                $title ='';
                $hotelDatas = $this->doccin_mViewStats($datas, $consql, $con);

            }else{
                if($datas['month']==0){
                    $hotelDatas = $this->doccin_bydates($datas, $nums, $consql, $con);
                }else{
                    $tabledatas = $this->doccin_table($datas, $consql, $con);
                    //print_r($tabledatas);exit;
                    $hotelDatas = $this->doccin_bymons($datas, $nums, $consql, $con);
                }
                $title = $titleStr.' 入住率同比';
            }
    	}
    	echo json_encode(array('result'=>true,'msg'=>$hotelDatas,'title'=>$title,'subtitle'=>$datas['startDate'].'至'.$datas['endDate'],'tabledatas'=>$tabledatas));
    	exit;
    }
    //酒店排行
    public function doccin_rant($datas,$consql,$con){
    	$hotels = $this->model->query('select h.* from h_hotels h '.$consql['h'].' where h.hotel NOT LIKE  "%测试%"'.$con['h']);//所有酒店
    	$diffdays = getdiffdays($datas['startDate'], $datas['endDate']);
    	for($i=0;$i<count($hotels);$i++){
    		//$sql = 'select hd.hotel,SUM(hd.clientNo) as checkno from h_hotels_data hd'.$consql['g'].' where hd.hotelid='.$hotels[$i]['id'].' and hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'" '.$con['g'];
    		$sql = 'select hd.hotel,SUM(hd.clientNo) as checkno,AVG(hd.occupancyRate) as occurate from h_hotels_data hd'.$consql['g'].' where hd.hotelid='.$hotels[$i]['id'].' and hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'" '.$con['g'];
    		$list= $this->model->query($sql);
    		if(!$list[0]['hotel'])continue;
    		/*
    		if($datas['deviceType']=='all'){
    			$nums = $diffdays*($hotels[$i]['clientNo']+$hotels[$i]['clientNoPc']+$hotels[$i]['clientNoTv']);
    		}else{
    			$nums = $diffdays*$hotels[$i][$datas['flagTypes'][$datas['deviceType']]];
    		}
    		$occuArr[$i] = $nums==0?0:round($list[0]['checkno']/$nums*10000)/100;
    		*/
    		$occuArr[$i] = round($list[0]['occurate']*100)/100;
    		$listArr[$i] = array(
    			'hotel'=>$list[0]['hotel'],
    			'checkno'=>(int)$list[0]['checkno'],
    			'occurate'=>$occuArr[$i]
    		);
    	}
    	if(empty($listArr)){
    		echo json_encode(array('result'=>true,'msg'=>array()));
    		exit;
    	}
    	array_multisort($occuArr, SORT_DESC,$listArr);
    	$hotelDatas['newcnstr'] = '';
    	for($i=0;$i<20;$i++){
    		if(!$listArr[$i])break;
    		$hotelDatas['x'][$i] = $listArr[$i]['hotel'];
    		$hotelDatas['occurate'][$i] = $listArr[$i]['occurate'];
    		$hotelDatas['checkno'][$i] = $listArr[$i]['checkno'];
    	}
    	return $hotelDatas;
    }
    //根据月份获取入住率
    public function doccin_bymons($datas,$nums,$consql,$con){
    	$newcnarrs = array();//新增酒店入住数
    	if($datas['month']==1){
    		$weekmons = getOperWeeks($datas['startDate']);
    	}else{
    		$weekmons = array();
    		for($i=0;$i<$datas['month'];$i++){
    			$j = $i+1;
    			$mondate = date('Y-m-d',strtotime($datas['startDate'].'+'.$i.' month'));
    			$weekmons[$i] = array(
    				$mondate,
    				date('Y-m-d',strtotime($mondate.'+1 month -1 day')),
    				substr($mondate, 0,7)
    			);
    		}
    	}
    	foreach($weekmons as $key=>$weekmon){
    		$hotelDatas['x'][$key] = $weekmon[count($weekmon)-1];
//    		$totalnums = $nums*getdiffdays($weekmon[0], $weekmon[count($weekmon)-2]);
    		//$sql = 'select SUM(hd.clientNo) as checkno from h_hotels_data hd'.$consql['g'].' where hd.stime>="'.$weekmon[0].'" and hd.stime<="'.$weekmon[count($weekmon)-2].'" '.$con['g'];
    		$sql = 'select SUM(hd.clientNo) as checkno,AVG(hd.occupancyRate) as occurate from h_hotels_data hd'.$consql['g'].' where hd.stime>="'.$weekmon[0].'" and hd.stime<="'.$weekmon[count($weekmon)-2].'" '.$con['g'];
    		$list = $this->model->query($sql);
    		if(empty($list)){
    			$hotelDatas['occurate'][$key] = 0;
    			$hotelDatas['checkno'][$key] = 0;
    		}else{
    			foreach($list as $value){
    				//$hotelDatas['occurate'][$key] = $totalnums==0?0:round($value['checkno']/$totalnums*10000)/100;
    				$hotelDatas['checkno'][$key] = (int)$value['checkno'];
    				$hotelDatas['occurate'][$key] = round($value['occurate']*100)/100;
    			}
    		}
    		if($datas['hotelId']=='all'){
    			if(stripos($consql['g'], 'h_hotels h')===false){
    				$consql['g'] .= ' left join h_hotels h on h.id = hd.hotelid';
    			}
    			$newhotelcn = $this->model->query('select SUM(hd.clientNo) as checkno from h_hotels_data hd'.$consql['g'].' where hd.stime>="'.$weekmon[0].'" and hd.stime<="'.$weekmon[count($weekmon)-2].'" '.$con['g'].' and h.hotel NOT LIKE  "%测试%" and h.addtime>="'.$weekmon[0].'" and h.addtime<="'.$weekmon[count($weekmon)-2].'"');
    			$newcnstr[$key] = $newhotelcn[0]['checkno']?(int)$newhotelcn[0]['checkno']:0;
    		}
    	}
    	if(isset($newcnstr)){
			$hotelDatas['newcnstr'] =array(
				'name' => '新增酒店入住数',
				'type' => 'column',
				'yAxis' => 1,
				'data' =>$newcnstr,
				'tooltip' => array('valueSuffix'=>' 间')
			);
    	}else{
    		$hotelDatas['newcnstr'] = '';
    	}
    	return $hotelDatas;
    }
    //根据日期获取入住率
    public function doccin_bydates($datas,$nums,$consql,$con){
    	$sql = 'select SUM(hd.clientNo) as checkno,AVG(hd.occupancyRate) as occurate,hd.stime from h_hotels_data hd'.$consql['g'].'  where hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'" '.$con['g'].' group by hd.stime order by hd.stime';
        $list = $this->model->query($sql);
    	$hotelDatas['newcnstr'] = '';
    	if($datas['hotelId']=='all'){
    		if(stripos($consql['g'], 'h_hotels h')===false){
    			$consql['g'] .= ' left join h_hotels h on h.id = hd.hotelid';
    		}
    		$newhotelcn = $this->model->query('select SUM(hd.clientNo) as checkno,hd.stime from h_hotels_data hd'.$consql['g'].'  where hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'" '.$con['g'].' and h.hotel NOT LIKE  "%测试%" and h.addtime>="'.$datas['startDate'].'" and h.addtime<="'.$datas['endDate'].'" group by hd.stime order by hd.stime');
    		if($newhotelcn){
    			foreach($newhotelcn as $value){
    				$newhotelarr[$value['stime']] = (int)$value['checkno'];
    			}
    		}
    	}
    	if(empty($list)){
    		echo json_encode(array('result'=>true,'msg'=>array()));
    		exit;
    	}else{
    		foreach($list as $key=>$value){
    			$hotelDatas['x'][$key] = $value['stime'];
    			//$hotelDatas['occurate'][$key] = $nums==0?0:round($value['checkno']/$nums*10000)/100;
    			$hotelDatas['occurate'][$key] = round($value['occurate']*100)/100;
    			$hotelDatas['checkno'][$key] = (int)$value['checkno'];
    			$newcnstr[$key] = isset($newhotelarr[$value['stime']])?$newhotelarr[$value['stime']]:0;
    		}
    	}
    	$hotelDatas['newcnstr'] =array(
    			'name' => '新增酒店入住数',
    			'type' => 'column',
    			'yAxis' => 1,
    			'data' =>$newcnstr,
    			'tooltip' => array('valueSuffix'=>' 间')
    	);
    	return $hotelDatas;
    }
    //获取入住率表格
    public function doccin_table($datas,$consql,$con){
    	$results =$mons = array();
    	$alltypes = array('clientNo'=>'XS','clientNoPc'=>'PC','clientNoTv'=>'TV');
    	$hotels = $this->model->query('select h.*,hg.groupname from h_hotels h '.$consql['h'].' left join h_hotels_group hg on h.groupId=hg.id where h.hotel NOT LIKE  "%测试%"'.$con['h'].' order by h.groupId');//所有酒店
    	$t=0;
    	for($i=0;$i<count($hotels);$i++){
    		for($k=0;$k<$datas['month'];$k++){
    			$j = $k+1;
    			$mondate = date('Y-m-d',strtotime($datas['startDate'].'+'.$k.' month'));
    			$mons = array(
    				'mons' =>$mondate,
    				'mone' =>date('Y-m-d',strtotime($mondate.'+1 month -1 day')),
    				'mon' => substr($mondate, 0,7),
    				'days' => date('t',strtotime(substr($mondate, 0,7)))
    			);
    			//$sql = 'select hd.hotel,SUM(hd.clientNo) as checkno,hd.deviceType from h_hotels_data hd'.$consql['g'].' where hd.hotelid='.$hotels[$i]['id'].' and hd.stime>="'.$mons['mons'].'" and hd.stime<="'.$mons['mone'].'" '.$con['g'].' group by hd.deviceType';
    			$sql = 'select hd.hotel,SUM(hd.clientNo) as checkno,AVG(hd.occupancyRate) as occurate,hd.deviceType from h_hotels_data hd'.$consql['g'].' where hd.hotelid='.$hotels[$i]['id'].' and hd.stime>="'.$mons['mons'].'" and hd.stime<="'.$mons['mone'].'" '.$con['g'].' group by hd.deviceType';
    			$list= $this->model->query($sql);
    			if(!$list)continue;
    			$listTypes = array();
    			foreach($list as $value){
    				$listTypes[$value['deviceType']] = $value;
    			}
    			$pmssql = 'select * from `d_pms_data` where hotelid='.$hotels[$i]['id'].' and stime="'.$mons['mon'].'"';
    			$pmslist = $this->model->query($pmssql);
    			foreach($alltypes as $key=>$type){
    				$nums[$key] = $mons['days']*$hotels[$i][$key];
    				if(!isset($listTypes[$type]))continue;
    				$results[$t]['clientNo'][$key]['checkno']=(int)$listTypes[$type]['checkno'];
    				//$results[$t]['clientNo'][$key]['occurate'] = $nums[$key]==0?0:round($listTypes[$type]['checkno']/$nums[$key]*10000)/100;
    				$results[$t]['clientNo'][$key]['occurate']=round($listTypes[$type]['occurate']*100)/100;
    				if($key=='clientNo'&&$pmslist){
    					$results[$t]['clientNo'][$key]['pms'] = $pmslist[0]['occupancyRate'];
    					$difftmp = round(($results[$t]['clientNo'][$key]['occurate']-$pmslist[0]['occupancyRate'])*100)/100;
    					if($difftmp>0){
    						$results[$t]['clientNo'][$key]['diff'] = '+'.$difftmp;
    					}else{
    						$results[$t]['clientNo'][$key]['diff'] = $difftmp;
    					}
    				}else{
    					$results[$t]['clientNo'][$key]['pms'] =	$results[$t]['clientNo'][$key]['diff'] = '';
    				}
    				$results[$t]['clientNo'][$key]['roomsnum'] = $hotels[$i][$key];
    			}
    			$results[$t]['groupId'] = $hotels[$i]['groupId'];
    			$results[$t]['groupname'] = $hotels[$i]['groupname'];
    			$results[$t]['hotel'] = $hotels[$i]['hotel'];
    			$results[$t]['id'] = $hotels[$i]['id'];
    			$results[$t]['time'] = $mons['mon'];
    			$t++;
    		}
    	}
    	return $results;
    }
    //根据集团id选择酒店
    public function selHotelsByGp(){
    	if(!isset($_POST['groupId'])){
    		echo json_encode(array('result'=>false,'msg'=>'缺少信息'));
    		exit;
    	}
    	if($this->isSpecialAdmin()){
    		$uid=$_SESSION['manage_uid'];
    		$consql_h=' left join h_hotelsid_adminid ha on h.id=ha.hotelId ';
    		$conh=" and ha.adminId=".$uid;
    	}else{
    		$conh='';
    	}
    	if($_POST['groupId']!='all'){
    		$conh .= ' and h.groupId = '.$_POST['groupId'];
    	}
    	$sql = 'select h.id,h.hotel from h_hotels h '.$consql_h.' where h.hotel NOT LIKE  "%测试%"'.$conh;
    	$hotels = $this->model->query($sql);
    	if($hotels){
    		echo json_encode(array('result'=>true,'msg'=>$hotels));
    		exit;
    	}
    }
    //酒店总体数据统计
    public function totalcount(){
    	$adminGroup=$this->isSpecialAdmin();
    	if($adminGroup){
    		$uid=$_SESSION['manage_uid'];
    		$consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
    		$cong=" and a.adminId=".$uid;
    	}else{
    		$consql_g='';
    		$cong='';
    	}
    
    	$sql = "select h.*,hc.cityName,hg.groupname from h_hotels h  ".$consql_g." left join h_citys hc on LEFT( h.citycode, 2)=hc.assign left join h_hotels_group hg on h.groupId=hg.id where h.hotel NOT LIKE '%测试%' ".$cong." order by h.groupId,h.clientNo desc";
    	$list  =   $this->model->query($sql);
    	$onlinelist  = array();
    	$offlinelist  = array();
    	$time = time();
    	$pronums = array();
    	if ($list){
    		foreach($list as $key=>$hotel){
    			if(($time-$hotel['stime'])<900){
    				$onlinelist[] = array('name'=>$hotel['hotel'],'value'=>$hotel['cityName'],'geoCoord'=>array($hotel['lng']/100000000,$hotel['lat']/100000000));
    				$list[$key]['timestate']=0;
    				$pronums[$hotel['cityName']]['on']++;
    			}else{
    				$offlinelist[] = array('name'=>$hotel['hotel'],'value'=>$hotel['cityName'],'geoCoord'=>array($hotel['lng']/100000000,$hotel['lat']/100000000));
    				$list[$key]['timestate']=1;
    				$pronums[$hotel['cityName']]['off']++;
    			}
    		}
    		$this->assign("roomArr",$list);
    	}
    	$tcount = $this->doGetTcount($consql_g,$cong);
    	$this->assign('tcount',$tcount);
    	$this->assign('pronums',json_encode($pronums));
    	$this->assign('onlinelist',json_encode($onlinelist));
    	$this->assign('offlinelist',json_encode($offlinelist));
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['totalcount']);
    	$this->assign('hotels',$list);
    	$this->display("admin/totalcount");
    }
    public function sortTotalcount(){
    	if(!isset($_POST['cltype'])||!isset($_POST['clval'])){
    		echo json_encode(array('result'=>false,'msg'=>'排序失败'));
    		exit;
    	}else{
    		$type = $_POST['cltype'];
    		$val = $_POST['clval']=='desc'?'asc':'desc';
    	}
    	$adminGroup=$this->isSpecialAdmin();
    	if($adminGroup){
    		$uid=$_SESSION['manage_uid'];
    		$consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
    		$cong=" and a.adminId=".$uid;
    	}else{
    		$consql_g='';
    		$cong='';
    	}
    	
    	$sql = "select h.*,hc.cityName,hg.groupname from h_hotels h  ".$consql_g." left join h_citys hc on LEFT( h.citycode, 2)=hc.assign left join h_hotels_group hg on h.groupId=hg.id where h.hotel NOT LIKE '%测试%' ".$cong." order by h.groupId,h.".$type."  ".$val;
    	echo $sql;exit;
    	$list  =   $this->model->query($sql);
    	if($list){
    		echo json_encode(array('result'=>true,'msg'=>$list,'val'=>$val));
    		exit;
    	}else{
    		echo json_encode(array('result'=>false,'msg'=>'排序失败'));
    		exit;
    	}
    	 
    }
    //获取试运营酒店等数量
    public function doGetTcount($consql_g,$cong){
    	$cong .= ' and h.hotel NOT LIKE "%测试%"';
    	$today = date('Y-m-d',time());
    	$startDate = date('Y-m-d',strtotime("$today -3 months"));
    	$datas['all'] = $this->model->query('select * from h_hotels h '.$consql_g.' where 1 '.$cong);
    	$datas['test'] = $this->model->query('select * from h_hotels h '.$consql_g.' where h.addtime>="'.$startDate.'" '.$cong);
    	$datas['ok']= $this->model->query('select * from h_hotels h '.$consql_g.' where h.addtime>"1970-01-01" and h.addtime<"'.$startDate.'" '.$cong);
    	$tcount = array();
    	$keys = array('all','test','ok');
    	foreach($keys as $key){
    		$tcount['rooms'][$key]['xs'] = $tcount['rooms'][$key]['pc'] = $tcount['rooms'][$key]['tv'] =0;
    		$tcount['hotels'][$key] = count($datas[$key]);
            if($datas[$key]){
                foreach($datas[$key] as $value){
                    $tcount['rooms'][$key]['xs'] += $value['clientNo'];
                    $tcount['rooms'][$key]['pc'] += $value['clientNoPc'];
                    $tcount['rooms'][$key]['tv'] += $value['clientNoTv'];
                }
            }

    	}
    	return $tcount;
    }

    //目标统计
    public function targetStatistics(){
        $this->searchCondition();
        $this->assign('left', 'admin_targetStatistics');
        $this->display('admin/targetStatistics');
    }

    //获取目标统计表格
    public function doccin_targetStatistics($datas,$consql,$con){
        $results =$mons = array();
        $alltypes = array('clientNo'=>'XS','clientNoPc'=>'PC','clientNoTv'=>'TV');
        $hotels = $this->model->query('select h.*,hg.groupname from h_hotels h '.$consql['h'].' left join h_hotels_group hg on h.groupId=hg.id where h.hotel NOT LIKE  "%测试%"'.$con['h'].'  order by h.groupId');//所有酒店
        $t=0;
        $rowConfig=$this->model->query("SELECT * FROM `d_config` WHERE 1");
        if($rowConfig){
            foreach($rowConfig as $v){
                $arryConfig[$v['name']]=$v['config'];
            }
        }

        $contractSingle=$arryConfig['contract_price']/$arryConfig['contract_life'];  //单间合同价/合同年限
        $costSingle=$arryConfig['cost_price']/$arryConfig['contract_life'];  //单间成本价/合同年限
        $premium = $arryConfig['premium']; //溢价

        $monthCon= date('Y-m',strtotime($datas['startDate']));
        for($i=0;$i<count($hotels);$i++){
            $hotelCreatMonth=$hotels[$i]['addtime'];
            $monthCount=getMonthNum($monthCon,$hotelCreatMonth);
            //月开房数
            $sql = "select hd.hotel,SUM(hd.clientNo) as checkno,AVG(hd.occupancyRate) as occurate,hd.deviceType from h_hotels_data hd ".$consql['g']." where hd.hotelid=".$hotels[$i]['id']." and DATE_FORMAT(hd.stime,'%Y-%m')='".$monthCon."' ".$con['g']." group by hd.deviceType";
            $list= $this->model->query($sql);
            if(!$list)continue;
            $listTypes = array();
            foreach($list as $value){
                $listTypes[$value['deviceType']] = $value;
            }
            //累计月开房数
            $sqlTotal = "select hd.hotel,SUM(hd.clientNo) as checkno,hd.deviceType from h_hotels_data hd ".$consql['g']." where hd.hotelid=".$hotels[$i]['id']." and DATE_FORMAT(hd.stime,'%Y-%m')<='".$monthCon."' ".$con['g']." group by hd.deviceType";
            $listTotal= $this->model->query($sqlTotal);
            if(!$listTotal)continue;
            $listTotalTypes = array();
            foreach($listTotal as $value){
                $listTotalTypes[$value['deviceType']] = $value;
            }
            $pmssql = "select * from `d_pms_data` where hotelid=".$hotels[$i]['id']." and stime='".$monthCon."'";

            $pmslist = $this->model->query($pmssql);
            foreach($alltypes as $key=>$type){
                if(!isset($listTypes[$type]))continue;
                $results[$t]['clientNo'][$key]['checkno']=(int)$listTypes[$type]['checkno'];
                $results[$t]['clientNo'][$key]['occurate']=round($listTypes[$type]['occurate']*100)/100;
                $results[$t]['clientNo'][$key]['roomNo'] =$hotels[$i][$key];

                if($key=='clientNo'&&$pmslist){
                    $results[$t]['clientNo'][$key]['pms'] = $pmslist[0]['occupancyRate'];
                    $difftmp = round(($results[$t]['clientNo'][$key]['occurate']-$pmslist[0]['occupancyRate'])*100)/100;
                    if($difftmp>0){
                        $results[$t]['clientNo'][$key]['pmsdiff'] = '+'.$difftmp;
                    }else{
                        $results[$t]['clientNo'][$key]['pmsdiff'] = $difftmp;
                    }
                }else{
                    $results[$t]['clientNo'][$key]['pms'] =	$results[$t]['clientNo'][$key]['pmsdiff'] = '';
                }

                //目标合同 ：本月=合同价/合同年限*房间数    累计=本月*月数
                //目标成本： 本月=成本价/合同年限*房间数    累计=本月*月数
                $results[$t]['clientNo'][$key]['contract'] =round($hotels[$i][$key]*$contractSingle/10000,2);
                $results[$t]['clientNo'][$key]['cost'] =round($hotels[$i][$key]*$costSingle/10000,2);
                $results[$t]['clientNo'][$key]['contractTotal'] =round($hotels[$i][$key]*$contractSingle*$monthCount/10000,2);
                $results[$t]['clientNo'][$key]['costTotal'] =round($hotels[$i][$key]*$costSingle*$monthCount/10000,2);
                //回收： 本月=溢价*月开房数  累计=溢价*总开房数
                $results[$t]['clientNo'][$key]['recycle'] =round($premium*$results[$t]['clientNo'][$key]['checkno']/10000,2);
                $results[$t]['clientNo'][$key]['recycleTotal'] =round($premium*$listTotalTypes[$type]['checkno']/10000,2);
                //目标合同差异
                $results[$t]['clientNo'][$key]['diff'] = $results[$t]['clientNo'][$key]['recycle'] -  $results[$t]['clientNo'][$key]['contract'];
                $results[$t]['clientNo'][$key]['diffTotal'] = $results[$t]['clientNo'][$key]['recycleTotal'] - $results[$t]['clientNo'][$key]['contractTotal'];
                //目标成本差异
                $results[$t]['clientNo'][$key]['costdiff'] = $results[$t]['clientNo'][$key]['recycle'] -  $results[$t]['clientNo'][$key]['cost'];
                $results[$t]['clientNo'][$key]['costdiffTotal'] = $results[$t]['clientNo'][$key]['recycleTotal'] - $results[$t]['clientNo'][$key]['costTotal'];
            }


            $results[$t]['groupId'] = $hotels[$i]['groupId'];
            $results[$t]['groupname'] = $hotels[$i]['groupname'];
            $results[$t]['hotel'] = $hotels[$i]['hotel'];
            $results[$t]['id'] = $hotels[$i]['id'];
            $results[$t]['time'] = $monthCon;
            $t++;
        }
        return $results;
    }

    //根据日期获取酒店日常入住信息
    public function doccin_dailyCount($datas,$consql,$con){
        $sql = 'select SUM(hd.clientNo) as checkno,AVG(hd.occupancyRate) as occurate,hd.stime from h_hotels_data hd'.$consql['g'].'  where hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'" '.$con['g'].' group by hd.stime order by hd.stime';
        $list = $this->model->query($sql);
//echo $sql;
        if(empty($list)){
            echo json_encode(array('result'=>true,'msg'=>array()));
            exit;
        }else{
            foreach($list as $key=>$value){
                $hotelDatas['x'][$key] = $value['stime'];
                $hotelDatas['occurate'][$key] = round($value['occurate']*100)/100;
                $hotelDatas['checkno'][$key] = (int)$value['checkno'];
            }
            $hotelDatas['occurateTotal']=array_sum($hotelDatas['occurate']);
//            $hotelDatas['checknoTotal']=array_sum($hotelDatas['checkno']);
            $arryLength=count($hotelDatas['occurate']);
            $occuratePer=round($hotelDatas['occurateTotal']/$arryLength,2);
//            $hotelDatas['checknoPer']=round($hotelDatas['checknoTotal']/$arryLength,2);
            for($i=0;$i<$arryLength;$i++){
                $hotelDatas['occuratePer'][$i]=$occuratePer;
            }
        }

        $alltypes = array('XS'=>'clientNo','PC'=>'clientNoPc','TV'=>'clientNoTv');
        if($datas['deviceType']=='all'){
            $str='h.clientNo+h.clientNoPc+h.clientNoTv';
        }else{
            $str='h.'.$alltypes[$datas['deviceType']];
        }

        $sqlTotal='SELECT SUM( tt.checkno ) as checknoPerday , SUM( tt.checknoTotal ) as checknoTotal , SUM( tt.totalInfact ) as totalRoomCount,SUM( tt.occurate ) as occurateTotal , COUNT( tt.hotelid ) as hotelCount  FROM (select sum(hd.clientNo) as checknoTotal,AVG(hd.clientNo) as checkno, AVG( hd.occupancyRate ) AS occurate, hd.hotelid,count(hd.id)*('.$str.') AS totalInfact from h_hotels_data hd '.$consql['g'].' where  hd.stime>="'.$datas['startDate'].'" and hd.stime<="'.$datas['endDate'].'" '.$con['g'].' group by hd.hotelid )tt';
        $rowTotal= $this->model->query($sqlTotal);
        if($rowTotal){
            $hotelDatas['checknoPer']=round($rowTotal[0]['checknoPerday'],2);
            $hotelDatas['checknoTotal']=$rowTotal[0]['checknoTotal'];
            $hotelDatas['totalRoomCount']=$rowTotal[0]['totalRoomCount'];
            $hotelDatas['occuratePerTotal']=round( $rowTotal[0]['occurateTotal']/$rowTotal[0]['hotelCount'],2);
        }
//        $hotels = $this->model->query('select sum('.$str.') as totalRoomCount from h_hotels h '.$consql['h'].' left join h_hotels_group hg on h.groupId=hg.id where h.hotel NOT LIKE  "%测试%"'.$con['h']);//所有酒店
//        if($hotels){
//            $hotelDatas['totalRoomCount']=$hotels[0]['totalRoomCount'];
//        }
        return $hotelDatas;
    }
    //剧透社包管理
    public function wxpsPacks(){
    	require(CP_PATH.'ext/Page.class.php');
    	//获取页数ID
    	$page_id=intval($_GET['page']);
    	$url=__URL__.'/page?page='.$page_id;
    	$page=new Page();
    	//每页显示行数
    	$listRows=10;//每页显示的信息条数
    	//每页显示页数
    	$pageBarNum=5;
    	$cur_page=$page->getCurPage($url);
    	
    	$limit_start=($cur_page-1)*$listRows;
    	$limit=$limit_start.','.$listRows;
    	$limitStr='';
    	if($limit!=''){
    		$limitStr = " limit ".$limit;
    	}
    	
    	$con = ' where 1';//预留权限
    	
    	$sql = "select count(*) as zs from h_wxps_packages ".$con;
    	$row = $this->model->query($sql);
    	if ($row){
    		$count = $row[0][zs];
    	}
    	$sql = "select * from h_wxps_packages   ".$con."  order by lasttime desc ".$limitStr;
    	$list  =   $this->model->query($sql);
    	$totalnum = 0;
    	if ($list){
    		$this->assign('totalnum',$count);
    		$this->assign("pks",$list);
    		if($listRows>=$count){
    			$this->assign('page','');
    		}else{
    			$this->assign('page',$page-> show($url,$count,$listRows,$pageBarNum,$mode=5) );
    		}
    	}

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['wxpsPacks']);
    	$this->display('admin/wxpsPacks');
    }
    //修改素材包属性
    public function wxpsPacks_modify(){
    	if(!$_POST['type']||!$_POST['value']||!$_POST['pid']){
    		echo json_encode(array('result'=>false,'msg'=>'不能为空'));
    		exit;
    	}
    	$type = $_POST['type'];$value = $_POST['value'];$pid=$_POST['pid'];
    	$flag = $this->model->query('update `h_wxps_packages` set '.$type.' = "'.$value.'" where id='.$pid);
    	if($flag){
    		echo json_encode(array('result'=>true,'msg'=>'修改成功'));
    	}else{
    		echo json_encode(array('result'=>false,'msg'=>'修改失败'));
    	}
    	exit;
    }
    //上传素材页面-标题
    public function wxps_uploadpage(){
    	$this->display('admin/wxpsUpTitle');
    }
    //上传素材页面-页面
    public function wxps_doUpPage(){
    	if(!isset($_GET['key'])){
    		$this->wxps_uploadpage();
    		exit;
    	}
    	$pid = $_GET['key'];
    	$title = $this->model->query('select * from h_wxps_packages where id='.$pid);
    	if(!$title){
    		return false;
    	}else{
    		$this->assign('title',$title[0]['title']);
    		$this->assign('pid',$pid);
    		$this->display('admin/wxpsUpload');
    	}
    }
    //检测标题唯一性
    public function wxps_checkPksTitle(){
    	if(!isset($_POST['title'])){
    		echo json_encode(array('res'=>false,'msg'=>'查询失败'));
    		exit;
    	}
    	$title = trim($_POST['title']);
    	$list = $this->model->query('select * from h_wxps_packages where title = "'.$title.'"');
    	if($list){
    		echo json_encode(array('res'=>false,'msg'=>'该标题已经存在 请更换标题'));
    	}else{
    		echo json_encode(array('res'=>true,'msg'=>'ok'));
    	}
    	exit;
    }
    //新建指定标题的包
    public function wxps_addPksTitle(){
    	if(!isset($_POST['title'])){
    		echo json_encode(array('res'=>false,'msg'=>'生成失败'));
    		exit;
    	}
    	$title = trim($_POST['title']);
    	$time = time();
    	//$thumb = __PUBLIC__.'/images/jts_filebg.jpg';
    	$this->model->query("insert into h_wxps_packages (`title`,`address`,`state`,`lasttime`) values ('{$title}','jts/',0,{$time})");
    	$insertId = $this->model->insert_id();
    	if($insertId){
    		$packname = $insertId.'-'.$time;
    		$this->model->query('update h_wxps_packages set packname="'.$packname.'" where id='.$insertId);
    		echo json_encode(array('res'=>true,'msg'=>array('key'=>$insertId,'name'=>$title)));
    	}else{
    		echo json_encode(array('res'=>false,'msg'=>'生成失败'));
    	}
    	exit;
    }
    //上传素材
    public function wxpsPacks_upload(){
    	set_time_limit(0);
    	if(!isset($_FILES)||!isset($_POST['pid'])){
    		echo json_encode(array('res'=>false,'msg'=>'上传失败'));
    	}
    	$uploadMod = new UploadJts();
    	$pid = trim($_POST['pid']);
    	$list = $this->model->query('select * from h_wxps_packages where id='.$pid);
    	if(!$list){
    		echo json_encode(array('res'=>false,'msg'=>'上传失败'));
    	}
		$address = $list[0]['address'].$list[0]['packname'].'/';
    	$savepath = CP_PIE.'/public/'.$address;
    	if(!file_exists($savepath)){
    		mkdir($savepath,0777,true);
    	}
    	$uploadMod->savePath = $savepath;
    	$uploadMod->saveRule = cp_uniqid;
    	if(!$uploadMod->upload())
    	{
    		echo json_encode(array('res'=>false,'msg'=>'上传失败！ '.$uploadMod->getErrorMsg()));
    		exit;
    	}
    	else
    	{	
    		$time = time();
    		$files = $uploadMod->getUploadFileInfo();
    		$insertsql = "insert into h_wxps_libs (`name`,`pid`,`type`,`extension`,`size`,`fileinfo`,`addtime`,`address`) values ";
    		foreach($files as $val){
    			$fileinfo = '';
    			$insertsql.="('{$val['savename']}','{$pid}','".$val['type']."','{$val['extension']}',{$val['size']},'{$fileinfo}',{$time},'".$address."'),";
    		}
    		$insertsql = rtrim($insertsql,',');
    		$flag = $this->model->query($insertsql);
    		echo json_encode(array('res'=>true,'msg'=>$files));
    		exit;
    	}
    }
    //生成包
    public function wxpsPacks_doPack(){
    	set_time_limit(0);
    	if(!isset($_REQUEST['pid'])||!isset($_POST['libs'])){
    		echo json_encode(array('res'=>false,'msg'=>'信息不足'));
    		exit;
    	}
    	$pid = $_REQUEST['pid'];
    	$libs = $_POST['libs'];
    	foreach($libs as $lib){
    		$this->model->query('update h_wxps_libs set sortnum='.$lib['sortnum'].' where id='.$lib['id']);
    	}
    	$path = $this->model->query("select * from h_wxps_packages where id=".$pid.' and state=0');
    	if($path){
    		$zip = new Zip();
    		$savepath = CP_PIE.'/public/'.$path[0]['address'];
    		if(!file_exists($savepath)){
    			mkdir($savepath,0777,true);
    		}
    		$zipname =  $savepath.$path[0]['packname'].'.zip';
    		$zip = new ZipArchive();
    		$res = $zip->open($zipname, ZipArchive::CREATE); //不存在则创建
    		$list = $this->model->query('select * from h_wxps_libs where pid='.$pid);
    		if($list){
    			$flag = true;
    			$thumb = array();
    			$libids = '';
    			foreach($list as $value){
    				if(stripos($value['type'],'image')!==false){
    					 $thumb[] = $value['address'].$value['packname'].$value['name'];
    				}
    				$libids.=$value['id'].',';
    				$flag = $flag&&$zip->addFile(CP_PIE.'/public/'.$value['address'].$value['name'],$value['name']);
    			}
    			$zip->close();
    			$size = filesize($zipname);
    			if(empty($thumb)){
    				$thumbPic = '';
    			}else{
    				$thumbPic = $thumb[0];
    			}
    			if($flag){
    				$time = time();
    				$res = $this->model->query("update h_wxps_packages set thumb='{$thumbPic}',size={$size},state=1,libids='{$libids}',lasttime={$time} where id={$pid}");
    				if($res){
    					echo json_encode(array('res'=>true,'msg'=>'打包成功'));
    					exit;
    				}else{
    					echo json_encode(array('res'=>false,'msg'=>'未知错误'));
    					exit;
    				}
    			}
    		}else{
    			echo json_encode(array('res'=>false,'msg'=>'没有素材'));
    			exit;
    		}
    		
    	}else{
    		echo json_encode(array('res'=>false,'msg'=>'打包失败'));
    		exit;
    	}
    }
    //获取素材
    public function wxpsPacks_getLibs(){
    	if(!isset($_REQUEST['pid'])){
    		echo json_encode(array('res'=>true,'msg'=>'信息不足'));
    		exit;
    	}
    	$pid = $_REQUEST['pid'];
    	$libs = $this->model->query('select * from h_wxps_libs where pid ='.$pid.' order by extension');
    	if(!$libs){
    		$libs = array();
    	}else{
    		for($i=0;$i<count($libs);$i++){
    			$src = __PUBLIC__.'/'.$libs[$i]['address'].$libs[$i]['name'];
    			if(stripos($libs[$i]['type'],'image')!==false){
    				$libs[$i]['prehtml'] = "<img width='80px' height='40px;' src='".$src."' class='file-preview-image' alt='".$libs[$i]['name']."' title='".$libs[$i]['name']."'>";
    			}else if(stripos($libs[$i]['type'],'mp3')!==false){
    				$libs[$i]['prehtml'] = '<audio class="kv-preview-data" controls><source  width="80px" height="40px;" src="'.$src.'" type="'.$libs[$i]['type'].'">'.$libs[$i]['name'].'</audio>';
    			}else if(stripos($libs[$i]['type'],'text')!==false){
    				$libs[$i]['prehtml'] = '<textarea   width="100px" height="60px"  class="kv-preview-data file-preview-text" title="'.$libs[$i]['name'].'" readonly>'.$src.'</textarea>';
    			}else if(stripos($libs[$i]['type'],'pdf')!==false){
    				$libs[$i]['prehtml'] = '<embed  width="200px" height="60px"  class="kv-preview-data" src="'.$src.'" type="application/pdf">';
    			}else if(stripos($libs[$i]['type'],'mp4')!==false){
    				$libs[$i]['prehtml'] = '<video   width="160px" height="80px"  class="kv-preview-data" controls><source width="80px" height="40px"  src="'.$src.'" type="'.$libs[$i]['type'].'">'.$libs[$i]['name'].'</video>';
    			}else{
    				$libs[$i]['prehtml'] = '<div  width="100px"  height="60px"  class="kv-preview-data file-preview-other-frame">'.$libs[$i]['name'].'</div>';
    			}
    		}
    	}
    	echo json_encode(array('res'=>true,'msg'=>$libs));
    	exit;
    }
    //删除素材
    public function wxpsPacks_deleteLib(){
    	if(!isset($_POST['id'])){
    		echo json_encode(array('res'=>false,'msg'=>'缺标题'));
    		exit;
    	}
		$list = $this->model->query('select * from h_wxps_libs where id='.$_POST['id']);
		if($list){
			$file = $savepath = CP_PIE.'/public/'.$list[0]['address'].$list[0]['name'];
			if(is_file($file)){
				if(unlink($file)){
					$flag = $this->model->query('delete from h_wxps_libs where id ='.$_POST['id']);
				}else{
					echo json_encode(array('res'=>false,'msg'=>'删除失败'));
					exit;
				}
			}
			
		}
    	echo json_encode(array('res'=>true,'msg'=>$flag));
    	exit;
    }
    //删除素材包
    public function wxpsPacks_del(){
    	if(!$_POST['pid']||!isset($_POST['state'])){
    		echo json_encode(array('result'=>false,'msg'=>'不能为空'));
    		exit;
    	}
    	$pid = $_POST['pid'];
    	$pack = $this->model->query('select * from `h_wxps_packages` where id='.$pid);
    	if($pack){
    		if($pack[0]['packname']){
    			$packfile =  CP_PIE.'/public/'.$pack[0]['address'].$pack[0]['packname'];
    			if($_POST['state']==0){
    				$libs = $this->model->query('select * from `h_wxps_libs` where pid='.$pid);
    				if($libs){
    					echo json_encode(array('res'=>false,'msg'=>'目录不为空,请先删除素材'));exit;
    				}else{
    					if(is_dir($packfile)){
    						rmdir($packfile);
    					}
    					$this->model->query('delete from `h_wxps_packages` where id = '.$pid);
    					echo json_encode(array('res'=>true,'msg'=>'删除成功'));exit;
    				}
    			}else{
    				$zipfile = $packfile.'.zip';
    				if(is_file($zipfile)){
    					unlink($zipfile);
    				}
    				$this->model->query('update `h_wxps_packages` set state=0 where id = '.$pid);
    				echo json_encode(array('res'=>true,'msg'=>'此操作仅删除包,还须删除源文件'));
    				exit;
    			}
    		}
    	}else{
    		echo json_encode(array('res'=>false,'msg'=>'删除包失败'));
    	}
    	exit;
    }
    //剧透社分发管理
    public function wxpsSends(){
    	if(!isset($_GET['type'])){
    		$type = 1;
    	}else{
    		$type = $_GET['type'];
    	}
    	switch($type){
    		case 1:
    			$this->wxpsNoSends();
    			break;
    		case 2:
    			$this->wxpsSendeds();
    			break;
    		default:
    			$this->wxpsNoSends();
    	}
    }
    //未下发
    public function wxpsNoSends(){
    	$packs = $this->model->query('select * from h_wxps_packages where  state =1 order by lasttime desc');
    	$adminGroup=$this->isSpecialAdmin();
    	if($adminGroup){
    		$uid=$_SESSION['manage_uid'];
    		$consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
    		$cong=" and a.adminId=".$uid;
    	}else{
    		$consql_g='';
    		$cong='';
    	}
    	$hotels = $this->model->query('select * from h_hotels h '.$consql_g.' where 1 '.$cong);
    	$this->assign('packs', $packs);
    	$this->assign('hotels', $hotels);
    	$this->assign("left",'admin_wxpsSends');

    	$this->display('admin/wxpsSends');
    }
    //已下发
    public function wxpsSendeds(){
    	$packs = $this->model->query('select * from h_wxps_packages where  state = 2 order by lasttime desc');
    	$adminGroup=$this->isSpecialAdmin();
    	if($adminGroup){
    		$uid=$_SESSION['manage_uid'];
    		$consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
    		$cong=" and a.adminId=".$uid;
    	}else{
    		$consql_g='';
    		$cong='';
    	}
    	$this->assign('packs', $packs);
    	$this->assign("left",'admin_wxpsSends');
    	$this->display('admin/wxpsSendeds');
    }
    //执行下发
    public function wxpsDoSend(){
    	if(!isset($_POST['packid'])){
    		echo json_encode(array('result'=>false,'msg'=>'信息不足'));
    		exit;
    	}
    	$packid = $_POST['packid'];
    	$list = $this->model->query('select * from h_wxps_packages where id='.$packid);
    	if(!$list){
    		echo json_encode(array('result'=>false,'msg'=>'信息不足'));
    		exit;
    	}
    	$packs = $list[0];
    	$hotels = $_POST['hotels'];
    	$time = time();
    	for($i=0;$i<count($hotels);$i++){
    		$url='http://'.$hotels[$i]['address'].'/'.$hotels[$i]['hotel'].'/jts/addPacks';
    		$list = $this->model->query('select * from h_wxps_sends where packid='.$packid.' and hotelid='.$hotels[$i]['id']);
    		if(!$list){
    			$this->model->query("insert into `h_wxps_sends` (`packid`, `hotelid` , `state`, `time`) values ({$packid},{$hotels[$i]['id']},0,$time)");//存表
    			$packs['sid'] = $this->model->insert_id();
    			$libs = $this->model->query('select * from h_wxps_libs where pid='.$packid);
    			$packsjson = json_encode($packs);
    			$libsjson = json_encode($libs);
    			$flag = wxps_curl_post($url,array('packs'=>$packsjson,'libs'=>$libsjson));
    			$this->model->query('update h_wxps_packages set state=2,lasttime='.$time.' where id='.$packid);
    		}else{
    			echo json_encode(array('result'=>false,'msg'=>'不能重复下发'));
    			exit;
    		}
    		echo $flag;
    	}
    	exit;
    }
    //已下发
    public function wxps_getSendeds(){
    	$packs = $this->model->query('select * from h_wxps_packages where  state = 2 order by addtime desc');
    	$adminGroup=$this->isSpecialAdmin();
    	if($adminGroup){
    		$uid=$_SESSION['manage_uid'];
    		$consql_g=' left join h_hotelsid_adminid a on h.id=a.hotelId ';
    		$cong=" and a.adminId=".$uid;
    	}else{
    		$consql_g='';
    		$cong='';
    	}
    	if($packs){
    		echo json_encode(array('res'=>true,'msg'=>$packs));
    	}else{
    		echo json_encode(array('res'=>false,'msg'=>'暂时没有已下发数据'));
    	}
    	exit;
    }
    //获取已下发详情
    public function wxps_getSendsInfo(){
    	if(!isset($_POST['packid'])){
    		echo json_encode(array('res'=>false,'msg'=>'暂无数据'));exit;
    	}
		$sends = $this->model->query('select ws.*,h.hotel from h_wxps_sends ws left join h_hotels h on ws.hotelid=h.id where packid ='.$_POST['packid'].' order by ws.state desc,time desc');
		if($sends){
			for($i=0;$i<count($sends);$i++){
				switch($sends[$i]['state']){
					case 0:
						$sends[$i]['bgclass'] = ' class="info"';$sends[$i]['statinfo'] = '下载中';
						break;
					case 1:
						$sends[$i]['bgclass'] = ' class="success"';$sends[$i]['statinfo'] = '下载成功';
						break;
					case 2:
						$sends[$i]['bgclass'] = ' class="danger"';$sends[$i]['statinfo'] = '下载错误';
						break;
					default:
						$sends[$i]['bgclass'] = '';$sends[$i]['statinfo'] = '';
				}
				$sends[$i]['timeformat'] = date('Y-m-d H:i:s',$sends[$i]['time']);
				$sends[$i]['completed'] = sizecountByB($sends[$i]['completedLength']);
				$sends[$i]['speed'] = sizecountByB($sends[$i]['downloadSpeed']);
			}
			echo json_encode(array('res'=>true,'msg'=>$sends));exit;
		}else{
			echo json_encode(array('res'=>false,'msg'=>'暂无数据'));exit;
		}
    }
    //获取下发最新状态
    public function wxps_newState(){
    	if(!isset($_POST['sid'])){
    		echo json_encode(array('res'=>false,'msg'=>'缺少条件'));
    		exit;
    	}
    	$sid = $_POST['sid'];
    	$list = $this->model->query('select * from h_wxps_sends where id='.$sid);
    	if(!$list){
    		echo json_encode(array('res'=>false,'msg'=>'找不到'));
    		exit;
    	}
    	$send = $list[0];
    	$time = time();
    	if($send['state']>=1){
    		$return['timeformat'] = date('Y-m-d H:i:s',$time);
    		$return['button'] = '';
    		$return['completed'] = sizecountByB($send['completedLength']);
    		$return['speed'] = sizecountByB($send['downloadSpeed']);
    		$return['statinfo']='下载完成';
    		$return['bgClass']='success';
    		echo json_encode(array('res'=>true,'msg'=>$return));
    		exit;
    	}
    	if(!$send['ariagid']){
    		echo json_encode(array('res'=>false,'msg'=>'酒店尚未开始任务'));
    		exit;
    	}
    	$hotel = $this->model->query('select * from h_hotels where id='.$send['hotelid']);
    	if(!$hotel){
    		echo json_encode(array('res'=>false,'msg'=>'酒店信息出错'));
    		exit;
    	}
    	$hotelip = $hotel[0]['ipaddr'];
    	$hotelname = $hotel[0]['hotelName'];
    	if(strpos($hotelip, ':')!==false){
    		$rpcip = strstr($hotelip, ':',true);
    	}else{
    		$rpcip = $hotelip;
    	}
    	$arUrl = 'http://'.$rpcip.':6800/jsonrpc';
    	$aria2 = new Aria2($arUrl);
    	$statAll = $aria2->tellStatus($send['ariagid']);
    	$stat = $statAll['result'];
    	$return = array();
    	$return['timeformat'] = date('Y-m-d H:i:s',$time);
    	$return['button'] = '';
    	if(!$stat['errorCode']||$stat['errorCode']==0){
    		$return['completed'] = sizecountByB($stat['completedLength']);
    		$return['speed'] = sizecountByB($stat['downloadSpeed']);
    		if($stat['status']=='complete'){
    			$sql = 'update h_wxps_sends set state=1,time='.$time.',completedLength='.$stat['completedLength'].',downloadSpeed='.$stat['downloadSpeed'].',errorCode="'.$stat['errorCode'].'"  where id='.$sid;
    			$this->model->query($sql);
    			$return['statinfo']='下载完成';
    			$return['bgClass']='success';
    			//$vpnUrl = 'http://'.$hotelip.'/'.$hotelname.'/jts/stopAriaStat';
    			//$postdata =array('localid'=>$send['remoteid']);
    			//$stat=jtsCurlpost($vpnUrl,$postdata);
    		}else{
    			$sql = 'update h_wxps_sends set time='.$time.',completedLength='.$stat['completedLength'].',downloadSpeed='.$stat['downloadSpeed'].',errorCode="'.$stat['errorCode'].'"  where id='.$sid;
    			$this->model->query($sql);
    			$return['statinfo']='下载中';
    			$return['button']='<button onclick="reState('.$sid.')" class="btn btn-info">刷新</button>';
    			$return['bgClass']='info';
    		}
    	}else{
    		$return['completed'] = 0;
    		$return['speed'] = 0;
    		$return['statinfo']='下载错误';
    		$return['bgClass']='danger';
    		$sql = 'update h_wxps_sends set state=2,time='.$time.',errorCode="'.$stat['errorCode'].'",state=2 where id='.$sid;
    		$this->model->query($sql);
    	}
    	echo json_encode(array('res'=>true,'msg'=>$return));
    	exit;
    }
    //剧透社信息统计
    public function wxpsStats(){
        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['wxpsStats']);
    	$this->display('admin/wxpsStats');
    }

    //酒店业务流程管理
    public function process(){
        $this->searchCondition();

        $this->assign("menuConfigArry",$_SESSION['manage_MenuConfigArry']['process']);
        $this->display('admin/process');
    }
    //获取酒店属性
    public function getHotelsAttribute(){
        if(!isset($_POST['datas'])){
            echo json_encode(array('result'=>false,'msg'=>'查询失败'));
            exit;
        }
        $adminGroup=$this->isSpecialAdmin();
        if($adminGroup){
            $uid=$_SESSION['manage_uid'];
            $consql['h'] = ' left join h_hotelsid_adminid hd on h.id=ha.hotelId ';
            $con['h'] = " and hd.adminId=".$uid;
        }else{
            $con['h'] = $consql['h']  ='';
        }
        $datas = $_POST['datas'];

        if($datas['groupId']!='all'){
            $con['h'].=' and h.groupId='.$datas['groupId'];
        }

        switch($datas['cate']){
            case 1:
                $content='采买';
                break;
            case 2:
                $content='溢价回收';
                break;
            case 3:
                $content='赠送';
                break;
            default:
                $content='';
                break;
        }
        if($content){
            $consql['h'] .= ' left join h_hotelsid_attributeid ha on h.id=ha.hotelId ';
            $con['h'] .= " and ha.content='".$content."'";
        }

        if($datas['hotelId']!='all'){
            $con['h'].=' and h.id='.$datas['hotelId'];
        }

        $sql="SELECT * FROM `h_hotels_attribute` WHERE isShow=1 order by `aorder`,id";
        $rowAttribute=$this->model->query($sql);
        $arryAttribute=array();
        if($rowAttribute){
            foreach($rowAttribute as $k=>$v){
                $arryAttribute['name'][$v['attributeFlag']] = $v['attributeName'] ;
                $arryAttribute['content'][$v['attributeFlag']] = '' ;
            }
        }

        $sql="SELECT h.id,h.`hotelName`, h.`hotel`, h.`groupId`, h.`clientNo`, h.`clientNoPc`, h.`clientNoTv` FROM `h_hotels` h  ".$consql['h'] ." WHERE h.hotel NOT LIKE  '%测试%' ". $con['h'];
        $arryResult=array();
        $rowHotels=$this->model->query($sql);
        $arryProcess=array();
        if($rowHotels){
            foreach($rowHotels as $k=>$h){
                $arryProcess[$k]['content']=$arryAttribute['content'];
                $arryProcess[$k]['hotel']=$h;
                $sqlContent="SELECT ha.*,ii.content,ii.editTime FROM `h_hotels_attribute`  ha  left join h_hotelsid_attributeid ii on ha.id=ii.attributeid WHERE ii.hotelId=".$h['id'];
                $rowContent = $this->model->query($sqlContent);
                if($rowContent){
                    foreach( $rowContent as $c){
                        if($c['attributeFlag']=='paymentDateMonth'){
                            $arryProcess[$k]['content']['localMonth'] = $c['editTime'];
                        }
                        $arryProcess[$k]['content'][$c['attributeFlag']] = $c['content'];
                    }
                }
                $productNum ='';
                $productName ='';
                $clientNo = $h['clientNo'];
                $clientNoPc = $h['clientNoPc'];
                $clientNoTv = $h['clientNoTv'];
                if($clientNo){
                    $productNum .= $clientNo.';';
                    $productName .= '投影;';
                }
                if($clientNoPc){
                    $productNum .= $clientNoPc.';';
                    $productName .= '盒子;';
                }
                if($clientNoTv){
                    $productNum .= $clientNoTv.';';
                    $productName .= '电视;';
                }
                $arryProcess[$k]['content']['productNum'] = substr($productNum,0,-1);
                $arryProcess[$k]['content']['productName'] = substr($productName,0,-1);

            }
        }

        if($datas['cate']==2){
            //财务详情
            $arryTotalType= array(
                "paymentDateTotal" => "paymentDateMonth",
                "receivableTotal" => "receivableMonth",
                "actualTotal" => "actualMonth"
            );
            foreach($arryTotalType as $key=>$val){
                $sqlDetial= "SELECT ii.*,h.hotel FROM `h_hotels_attribute` ha  left join h_hotelsid_attributeid ii on ha.id=ii.attributeid left join `h_hotels` h on ii.hotelId=h.id WHERE  ha.attributeFlag='{$val}' order by ii.editTime asc";
                $rowDetial=$this->model->query($sqlDetial);
                if($rowDetial){
                    foreach($rowDetial as $m){
                        $arryResult[$m['hotelId']]['hotelName']=$m['hotel'];
                        $localMonth= $m['editTime'];
                        $arryResult[$m['hotelId']]['data'][$localMonth][$val]=$m['content'];

                    }
                }
            }
            $_SESSION['detialAttribute']=$arryResult;
            $_SESSION['processAttribute']=$arryProcess;
        }
        echo json_encode(array('result'=>true,'msg'=>$arryAttribute,'tabledatas'=>$arryProcess,'detial'=>$arryResult));
        exit;
    }

    //编辑业务属性
    public function editProcess(){
        $data = $_POST['arr'];
        $permissionid=$_SESSION['manage_groupid'];
        $row=   $this->model->query("SELECT * FROM `h_permission` WHERE id=".$permissionid." and rolename='财务'");
        if($row){
            $flagAdmin=1;
        }else{
            $flagAdmin=0;
        }

        $dateNow= date('Y-m-d',time());
        $adminId=$_SESSION['manage_uid'];
        $hotelId = $data['hotelId'];
        $localMonth = $data['localMonth'];
        $error1='';
        foreach($data as $k=>$v){
            $dateNow= date('Y-m-d',time());
            $strCon='';
            switch($k){
                case 'productNum':
                case 'productName':
                case 'paymentDateTotal':
                case 'receivableTotal':
                case 'actualTotal':
                     break;
                case 'paymentDateMonth':
                case 'receivableMonth':
                case 'actualMonth':
                    $dateNow = $localMonth;
                    if($dateNow){
                        $localMonth=date('Y-m',strtotime($localMonth));
                        $strCon = " and ii.editTime = '{$localMonth}'";
                    }else{
                        $error1='有效天数当月时间未选择';
                        break;
                    }
                case 'paymentMethod':
                case 'unitPrice':
                    if(!$flagAdmin){
                        $error2 = '抱歉，您没有修改财务相关数据的权限';
                        break;
                    }
                default :
                    $rowAttrId = $this->model->query("SELECT id FROM `h_hotels_attribute` WHERE `attributeFlag`='".$k."'");
                    if($rowAttrId){
                        $attrId= $rowAttrId[0]['id'];
                        $sqlContent="SELECT ii.content,ii.id FROM  h_hotelsid_attributeid ii  WHERE ii.hotelId=".$hotelId ." and ii.attributeId=".$attrId .$strCon;
                        $rowContent = $this->model->query($sqlContent);
                        if($rowContent){
                            $contentPre=$rowContent[0]['content'];
                            if($contentPre!=$v){
                                $contentId=$rowContent[0]['id'];
                                $sql="UPDATE `h_hotelsid_attributeid` SET   `content`='{$v}',`editTime`='{$dateNow}',`adminId`='{$adminId}' WHERE `id`=".$contentId;
                                $rowresult=$this->model->query($sql);
                            }
                        }else{
                            $rowresult=$this->model->query("INSERT INTO `h_hotelsid_attributeid`( `hotelId`, `attributeId`, `content`, `editTime`, `adminId`) VALUES ('{$hotelId}','{$attrId}','{$v}','{$dateNow}','{$adminId}')");
                        }
                    }
                    break;
            }
        }

        if($flagAdmin){
            $arryTotalType= array(
                "paymentDateTotal" => "paymentDateMonth",
                "receivableTotal" => "receivableMonth",
                "actualTotal" => "actualMonth"
            );
            foreach($arryTotalType as $k =>$v){
                $rowTotal=$this->model->query("SELECT sum(ii.content) as content FROM `h_hotels_attribute`  ha  left join h_hotelsid_attributeid ii on ha.id=ii.attributeid WHERE ii.hotelid='{$hotelId}' and ha.attributeFlag='{$v}'");
                if($rowTotal){
                    $contentTotal= $rowTotal[0]['content'];
                    $rowAttrId = $this->model->query("SELECT id FROM `h_hotels_attribute` WHERE `attributeFlag`='".$k."'");
                    if($rowAttrId){
                        $attrId= $rowAttrId[0]['id'];
                        $sqlContent="SELECT ii.content,ii.id FROM  h_hotelsid_attributeid ii  WHERE ii.hotelId=".$hotelId ." and ii.attributeId=".$attrId ;
                        $rowContent = $this->model->query($sqlContent);
                        if($rowContent){
                            $contentId=$rowContent[0]['id'];
                            $sql="UPDATE `h_hotelsid_attributeid` SET   `content`='{$contentTotal}',`editTime`='{$dateNow}',`adminId`='{$adminId}' WHERE `id`=".$contentId;
                            $rowresultTotal=$this->model->query($sql);
                        }else{
                            $rowresultTotal=$this->model->query("INSERT INTO `h_hotelsid_attributeid`( `hotelId`, `attributeId`, `content`, `editTime`, `adminId`) VALUES ('{$hotelId}','{$attrId}','{$contentTotal}','{$dateNow}','{$adminId}')");
                        }
                    }
                }
            }
        }
        if($flagAdmin){
            $json='{"msg":"1","data":"'.$error1.'"}';
        }else{
            $json='{"msg":"1"}';
        }
        echo $json;
        exit;
    }

    //获取酒店某月数据
    public function getAttrMonthData(){
        $hotelId = $_POST['hotelId'];
        $localMonth = $_POST['localMonth'];
        $arryTotalType= array(
            "paymentDateTotal" => "paymentDateMonth",
            "receivableTotal" => "receivableMonth",
            "actualTotal" => "actualMonth"
        );
        $arryResult=array();
        foreach($arryTotalType as $k=>$v){
            $row=$this->model->query("SELECT ii.content FROM `h_hotels_attribute` ha  left join h_hotelsid_attributeid ii on ha.id=ii.attributeid WHERE ii.hotelid='{$hotelId}' and ii.`editTime`='".$localMonth."' and ha.attributeFlag='{$v}'");
            if($row){
                $arryResult[$v]=$row[0]['content'];
            }else{
                $arryResult[$v]='';
            }
            $row=$this->model->query("SELECT sum(ii.content) as contentTotal FROM `h_hotels_attribute` ha  left join h_hotelsid_attributeid ii on ha.id=ii.attributeid WHERE ii.hotelid='{$hotelId}' and ii.`editTime`<='".$localMonth."' and ha.attributeFlag='{$v}'");
            if($row){
                $arryResult[$k]=$row[0]['contentTotal'];
            }
        }

        echo '{"msg":'.json_encode($arryResult).'}';
        exit;
    }

    //酒店业务数据导出
    public function getProcessExportData(){
        $flag=$_GET['flag'];

        if($flag==1){
            //溢价回收表
            $arryProcess=$_SESSION['processAttribute'];
            if($arryProcess){
                $headArry=array(
                    'A'=> '合同编号',
                    'B'=> '合同开始日期',
                    'C'=> '合同结束日期',
                    'D'=> '合同方',
                    'E'=> '酒店名称',
                    'F'=> '产品型号',
                    'G'=> '采购数量',
                    'H'=> '开始收款日期',
                    'I'=> '单价',
                    'J'=> '收款方式'
                );

                $exportDataArry=array();
                $num=1;
                foreach($arryProcess as $v){
                    $num++;
                    $exportData=array(
                        'A'.$num=> $v['content']['contractNo'],
                        'B'.$num=> $v['content']['contractStartTime'],
                        'C'.$num=> $v['content']['contractEndTime'],
                        'D'.$num=> $v['content']['storeName'],
                        'E'.$num=> $v['hotel']['hotel'],
                        'F'.$num=> $v['content']['productModel'],
                        'G'.$num=> $v['content']['productNum'],
                        'H'.$num=> $v['content']['startDate'],
                        'I'.$num=> $v['content']['unitPrice'],
                        'J'.$num=> $v['content']['paymentMethod'],
                    );
                    array_push($exportDataArry,$exportData);
                }
                $this->exportData($headArry,$exportDataArry);
            }

        }else{

            $detialData=$_SESSION['detialAttribute'];
            //溢价回收详情表
            if($detialData){
                $headArry=array(
                    'A'=> '酒店名',
                    'B'=> '月份',
                    'C'=> '有效收款天数',
                    'D'=> '应收金额',
                    'E'=> '实际回收金额'
                );

                $exportDataArry=array();
                $num=1;
                foreach($detialData as $ver){
                    $hotelName = $ver['hotelName'];
                    $data = $ver['data'];
                    foreach($data as $k => $v){
                        $num++;
                        $exportData=array(
                            'A'.$num=> $hotelName,
                            'B'.$num=> $k,
                            'C'.$num=> $v['paymentDateMonth'],
                            'D'.$num=> $v['receivableMonth'],
                            'E'.$num=> $v['actualMonth']
                        );
                        array_push($exportDataArry,$exportData);
                    }
                }
                $this->exportData($headArry,$exportDataArry);
            }
        }
        exit;
    }

    //统计数据导出
    public function dataStatistics(){
        $month=$_GET['month'];
        if($month){
            $date=date("Ym",strtotime($month));
        }else{
            $date=date("Ym",time());
        }
        $sql="SELECT hh.`id` , hh.`hotel` , hh.clientNo, hh.`clientNoTv` ,hh.`clientNoPc` , hh.`addtime` , cx.`cityName` AS cx, cc.`cityName` AS cc, cp.`cityName` AS cp, SUM(hd.`clientNo`) totalclientNo , SUM(FORMAT(hd.`totalLength` /3600,2) ) as ttotalLength, FORMAT(AVG(hd.`occupancyRate`),2) as toccupancyRate, hd.deviceType, COUNT(hd.id) as countDays"
            ." FROM  `h_hotels` hh LEFT JOIN h_citys cx ON hh.`citycode` = cx.`assign` LEFT JOIN h_citys cc ON cx.`parent` = cc.`assign` LEFT JOIN h_citys cp ON cc.`parent` = cp.`assign` LEFT JOIN  `h_hotels_data` hd ON hh.id = hd.hotelid WHERE hh.`hotel` NOT LIKE  '%测试%'"
            ." AND hh.`hotel` NOT LIKE  '%252%' AND hd.`dataLevel` =1 AND DATE_FORMAT( hd.stime, '%Y%m' ) = '{$date}' AND DATE_FORMAT( hh.addtime, '%Y%m') < '{$date}' GROUP BY hd.`hotelid` , hd.deviceType ORDER BY AVG(hd.`occupancyRate`) DESC ";
        $row=$this->model->query($sql);
        $dataArry=array();
        $countArry=array();
        $exportDataArry=array();
        $num=1;
        $countHotelFormal=0;
        if($row){
            foreach($row as $v){
                if($dataArry[$v['id']]){
                    $dataArry[$v['id']]+=$v['totalclientNo'];
                }else{
                    $dataArry[$v['id']]=$v['totalclientNo'];
                }

                $countHotelFormal++;
                $toccupancyRate=$v['toccupancyRate'];
                if($toccupancyRate>40){
                    $num++;
                    $exportData=array(
                        'A'.$num=> $v['id'],
                        'B'.$num=> $v['hotel'],
                        'C'.$num=> $v['clientNo'],
                        'D'.$num=> $v['clientNoTv']+$v['clientNoPc'],
                        'E'.$num=> $v['addtime'],
                        'F'.$num=> $v['cp'],
                        'G'.$num=> $v['cc'],
                        'H'.$num=> $v['cx'],
                        'I'.$num=> $v['totalclientNo'],
                        'J'.$num=> $v['ttotalLength'],
                        'K'.$num=> $v['toccupancyRate'],
                        'L'.$num=> $v['countDays'],
                    );
                    array_push($exportDataArry,$exportData);

                    $countArry['正式运营']['xsNo'] += $v['clientNo'];
                    $countArry['正式运营']['tvNo'] += $v['clientNoTv']+$v['clientNoPc'];
                }
            }

            $countArry['正式运营']['hotelNo']=$countHotelFormal;
        }
        $row2=$this->model->query("SELECT count(id) as c,sum(`clientNo`) as xsNo ,sum(`clientNoPc`+`clientNoTv`) as tvNo  FROM `h_hotels` WHERE `hotel` LIKE  '%252%'");
        if($row2){
            $countArry['单机']['hotelNo']=$row2[0]['c'];
            $countArry['单机']['xsNo']=$row2[0]['xsNo'];
            $countArry['单机']['tvNo']=$row2[0]['tvNo'];
        }
        $rowT=$this->model->query("SELECT count(id) as c,sum(`clientNo`) as xsNo ,sum(`clientNoPc`+`clientNoTv`) as tvNo  FROM `h_hotels` WHERE `hotel` NOT LIKE  '%测试%' and `hotel` NOT LIKE  '%252%'");
        if($rowT){
            $countArry['试运营']['hotelNo'] = $rowT[0]['c'] - $countArry['正式运营']['hotelNo'];
            $countArry['试运营']['xsNo'] = $rowT[0]['xsNo'] - $countArry['正式运营']['xsNo'];
            $countArry['试运营']['tvNo'] = $rowT[0]['tvNo'] - $countArry['正式运营']['tvNo'];
        }

        $num=$num+3;
        $exportData=array(
            'B'.$num=> '项目',
            'C'.$num=> '投影',
            'D'.$num=>  '电视',
            'E'.$num=> '酒店',
        );
        array_push($exportDataArry,$exportData);
        foreach($countArry as $k=>$ver){
            $num++;
            $exportData=array(
                'B'.$num=> $k,
                'C'.$num=>$ver['xsNo'],
                'D'.$num=>  $ver['tvNo'],
                'E'.$num=> $ver['hotelNo'],
            );
            array_push($exportDataArry,$exportData);
        }
        $num++;
        $exportData=array(
            'B'.$num=> '总计',
            'C'.$num=>  $countArry['正式运营']['xsNo']+$countArry['单机']['xsNo']+$countArry['试运营']['xsNo'],
            'D'.$num=>  $countArry['正式运营']['tvNo']+$countArry['单机']['tvNo']+$countArry['试运营']['tvNo'],
            'E'.$num=> $countArry['正式运营']['hotelNo']+$countArry['单机']['hotelNo']+$countArry['试运营']['hotelNo'],
        );
        array_push($exportDataArry,$exportData);
        $headArry=array(
            'A'=> 'id',
            'B'=> '酒店名',
            'C'=> '投影数',
            'D'=> '电视数',
            'E'=> '添加时间',
            'F'=> '省',
            'G'=> '市',
            'H'=> '县',
            'I'=> '点播次数',
            'J'=> '开机时长',
            'K'=> '入住率',
            'L'=> '开机天数'
        );

        $sql="SELECT  `hotelid` , hh.hotel, SUM(  `count` ) as countTotal,SUM( FORMAT(  `duration`  /3600,2)) as lengthTotal FROM  `h_hotels_data_movieday` hd LEFT JOIN h_hotels hh ON hh.id = hd.hotelid WHERE DATE_FORMAT( hd.stime,  '%Y%m' ) =  '{$date}' GROUP BY  `hotelid` ";
        $rowM=$this->model->query($sql);
        if($rowM){
            $num=$num+3;
            $exportData=array(
                'A'.$num=> '小帅电影数据',
            );
            array_push($exportDataArry,$exportData);
            $num++;
            $exportData=array(
                'A'.$num=> 'id',
                'B'.$num=> '酒店名',
                'C'.$num=> '点播次数',
                'D'.$num=> '时长（小时）',
                'E'.$num=> '月入住间数',
                'F'.$num=> '次数/日/间',
                'G'.$num=> '时长/日/间',
            );
            array_push($exportDataArry,$exportData);
            foreach($rowM as $m){
                $countRno=$dataArry[$m['hotelid']];
                if($countRno){
                    $num++;
                    $exportData=array(
                        'A'.$num=> $m['hotelid'],
                        'B'.$num=> $m['hotel'],
                        'C'.$num=> $m['countTotal'],
                        'D'.$num=> $m['lengthTotal'],
                        'E'.$num=> $countRno,
                        'F'.$num=> round($m['countTotal']/$countRno,2),
                        'G'.$num=> round($m['lengthTotal']/$countRno,2),
                    );
                    array_push($exportDataArry,$exportData);
                }
            }
        }

        $sql="SELECT  `hotelid` , hh.hotel, SUM(  `count` ) as countTotal,SUM( FORMAT(  `duration`  /3600,2)) as lengthTotal FROM  `h_hotels_data_m1905day` hd LEFT JOIN h_hotels hh ON hh.id = hd.hotelid WHERE DATE_FORMAT( hd.stime,  '%Y%m' ) =  '{$date}' GROUP BY  `hotelid` ";
        $rowM=$this->model->query($sql);
        if($rowM){
            $num=$num+3;
            $exportData=array(
                'A'.$num=> '风霆迅电影数据',
            );
            array_push($exportDataArry,$exportData);
            $num++;
            $exportData=array(
                'A'.$num=> 'id',
                'B'.$num=> '酒店名',
                'C'.$num=> '点播次数',
                'D'.$num=> '时长（小时）',
                'E'.$num=> '月入住间数',
                'F'.$num=> '次数/日/间',
                'G'.$num=> '时长/日/间',
            );
            array_push($exportDataArry,$exportData);
            foreach($rowM as $m){
                $countRno=$dataArry[$m['hotelid']];
                if($countRno){
                    $num++;
                    $F=round($m['countTotal']/$countRno,2);
                    $G=round($m['lengthTotal']/$countRno,2);
                    $exportData=array(
                        'A'.$num=> $m['hotelid'],
                        'B'.$num=> $m['hotel'],
                        'C'.$num=> $m['countTotal'],
                        'D'.$num=> $m['lengthTotal'],
                        'E'.$num=> $countRno,
                        'F'.$num=> $F,
                        'G'.$num=> $G
                    );
                    array_push($exportDataArry,$exportData);
                }
            }
        }

        $this->exportData($headArry,$exportDataArry);
    }

    public function sou_douban(){
        $name=$_POST['arr'];
//        $name='战狼2';
        $url= "https://api.douban.com/v2/movie/search?q=".$name;

        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        $obj=json_decode($file_contents);
        $subjectsArry = $obj -> subjects;
//        var_dump($subjectsArry);
        if(empty($subjectsArry)){
            $json='{"msg":"0"}';
        }else{
            $data=array();
            $i=0;
            foreach($subjectsArry as $v){
                $data[$i]['title'] = $v -> title;
                $data[$i]['id'] = $v -> id;
                $data[$i]['year'] = $v -> year;
                $data[$i]['genres'] = $v -> genres;
                $casts = $v -> casts;
                $castsArry=array();
                foreach($casts as $c){
                    $castsArry[]=$c->name;
                }
                $data[$i]['casts'] = $castsArry;
                $data[$i]['rating'] = $v -> rating ->average;

                $directors=$v -> directors ;
                $directorsArry=array();
                foreach($directors as $d){
                    $directorsArry[]=$d->name;
                }
                $data[$i]['directors'] = $directorsArry;
                $data[$i]['images'] = $v -> images ->medium;
                $i++;
            }
            $json= '{"msg":"1","moviedata":'.json_encode($data).'}';
        }
        echo $json;
        exit;
    }
    public function addDoubanData(){
        $name=$_POST['arr'];
//        $name='26363254';
        $url= "https://api.douban.com/v2/movie/subject/".$name;

        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        $obj=json_decode($file_contents);
        $data=array();
        $data['rating'] = $obj -> rating ->average;
        $data['collect_count'] = $obj -> collect_count ;
        $data['year'] = $obj -> year ;
        $data['countries'] = $obj -> countries ;
        $data['summary'] = $obj -> summary ;
        $data['genres'] = $obj -> genres;
        $data['title'] = $obj -> title;

        $casts = $obj -> casts;
        $castsArry=array();
        foreach($casts as $c){
            $castsArry[]=$c->name;
        }
        $data['casts'] = $castsArry;

        $directors=$obj -> directors ;
        $directorsArry=array();
        foreach($directors as $d){
            $directorsArry[]=$d->name;
        }
        $data['directors'] = $directorsArry;

//        echo "SELECT id FROM `h_movies` WHERE `movie_name`='".$data['title']."'";
        $row = $this->model->query("SELECT id FROM `h_movies` WHERE `movie_name`='".$data['title']."'");
        if($row){
            $json= '{"return":"0"}';
        }else{
            //简介@导演@主演@热度@时长@地区@上映时间@标签类型@评分@播放次数@分辨率@排序
            $movie_name= $data['title'];
            $movie_addr = 'http://219.146.255.198:8001/movie/';
            $movie_pic = 'http://219.146.255.198:8001/movie/';
            $movie_post = 'http://219.146.255.198:8001/movie/';
            $movie_trailer = 'http://219.146.255.198:8001/movie/';
            $Issuer = '华数';
            $time = time();
            $movie_menu='无所属分类';
            $movie_price=0;
            $details = $data['summary'];
            $director = implode(" ",$data['directors']);
            $actor =  implode(" ",$data['casts']);
            $hot = 'HOT';
            $movie_length = '';
            $movie_area = implode(" ",$data['countries']);
            $showtime = $data['year'] ;
            $label = implode(" ",$data['genres']);
            $score = $data['rating'] ;
            $playtimes = round($data['collect_count'] /10000,1).'万次播放';
            $resolution = '高清';
            $morder = 0;
            $language = 1;
            $movie_ss = '';
            $movie_content=$movie_menu.'#'.$movie_price.'#'.$details.'@'.$director.'@'.$actor.'@'.$hot.'@'.$movie_length.'@'.$movie_area.'@'.$showtime.'@'.$label.'@'.$score.'@'.$playtimes.'@'.$resolution.'@'.$morder.'#'.$language.'#'.$movie_ss;
            $sql="INSERT INTO `h_movies`( `movie_name`, `movie_addr`,`movie_trailer`, `movie_pic`, `movie_post`, `movie_content`,  `movie_stime`,Issuer) VALUES ('{$movie_name}','{$movie_addr}','{$movie_trailer}','{$movie_pic}','{$movie_post}','{$movie_content}','{$time}','{$Issuer}')";
            $this->model->query($sql);
            $insertId=$this->model->insert_id();
            $rowData = $this->model->query("SELECT * FROM `h_movies` WHERE `id`=".$insertId);
            $json= '{"return":"1","moviedata":'.json_encode($rowData[0]).'}';
//            $this->addStaffLog('添加电影','添加电影：'.$movie_name,'movie');
        }
        echo $json;
        exit;
    }


}


function trimall($str){
	$search = array(" ","　","\n","\r","\t");
	$replace = array("","","","","");
	return strtolower(str_replace($search, $replace, $str));
}
function storename($string){
	if(strpos($string,'/')!==false){
		$array = explode("/", $string);
		return sizecount($array[0]).'/'.sizecount($array[1]);
	}else{
		return sizecount($string);
	}
}
function sizecount($filesize){
	if ($filesize >= 1073741824){
		$filesize = round($filesize / 1073741824 * 100) / 100 .' TB';
	}elseif($filesize >= 1048576){
		$filesize = round($filesize / 1048576 * 100) / 100 .' GB';
	}elseif($filesize >= 1024){
		$filesize = round($filesize / 1024 * 100) / 100 . ' MB';
	}else{
		$filesize = $filesize.' KB';
	}
	return $filesize;
}
function sizecountByB($filesize){
	if ($filesize >= 1073741824){
		$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
	}elseif($filesize >= 1048576){
		$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
	}elseif($filesize >= 1024){
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	}else{
		$filesize = $filesize.' B';
	}
	return $filesize;
}
function matchname($name){
	if(strpos($name, '/')!==false||stripos($name,'network')!==false){
	    return 'storage';
	}else{
		return $name;
	}
}
function Sec2Time($time){
	if(is_numeric($time)){
		$return = '';
		$value = array(
			"years" => 0, "days" => 0, "hours" => 0,
			"minutes" => 0, "seconds" => 0,
		);
		if($time >= 31556926){
			$return.=floor($time/31556926).'年 ';
			$time = ($time%31556926);
		}
		if($time >= 86400){
			$return.=floor($time/86400).'天 ';
			$time = ($time%86400);
		}
		if($time >= 3600){
			$return.=floor($time/3600).'小时';
			$time = ($time%3600);
		}
		if($time >= 60){
			$return.=floor($time/60).'分';
			$time = ($time%60);
		}
		$return.=floor($time).'秒';
		Return $return;

	}else{
		return (bool) FALSE;
	}
}
function getOperWeeks($date){
	$time = strtotime($date);
	$startDate = date('Y-m-01',$time);
	$startstamp = strtotime($startDate);
	$mdays = date('t',$time);
	$endDate = date('Y-m-'.$mdays,$time);
	$i = 0;
	for($w = date('w',$startstamp);$w<7;$w++){
		$timestamp = $startstamp+$i*86400;
		$weeks[0][] = date('Y-m-d',$timestamp);
		$i++;
	}
	$weeks[0][$i] =  substr($weeks[0][0], -2).'至'.substr($weeks[0][$i-1],-2);
	$remains = $mdays-$i;
	$tmpnums = floor($remains/7);
	$modnum = $remains%7;
	for($j=1;$j<=$tmpnums;$j++){
		for($k=1;$k<=7;$k++){
			$timestamp+=86400;
			$weeks[$j][] = date('Y-m-d',$timestamp);
		}
		$weeks[$j][$k-1] =  substr($weeks[$j][0], -2).'至'.substr($weeks[$j][$k-2],-2);
	}
	if($modnum>0){
		for($e=1;$e<=$modnum;$e++){
			$timestamp+=86400;
			$weeks[$j][] = date('Y-m-d',$timestamp);
		}
		$weeks[$j][$e-1] =substr($weeks[$j][0], -2).'至'.substr($weeks[$j][$e-2],-2);
	}
	return $weeks;
}
function getdiffdays($startDate,$endDate){
	return (strtotime($endDate)-strtotime($startDate))/86400+1;
}

//两个日期相差的月数
function getMonthNum($date1,$date2){
    $date1_stamp=strtotime($date1);
    $date2_stamp=strtotime($date2);
    list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
    list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
    return abs(($date_1['y']-$date_2['y'])*12 +$date_1['m']-$date_2['m'])+1;
}
function wxps_curl_post($url,$post_data){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}
?>